java网络文件地址url的转换为MultipartFile文件流

2024-01-07 17:42:22

废话不多说,直接上代码
一、异常捕捉类

public class BusinessException extends RuntimeException {
    public BusinessException(String msg){
        super(msg);
    }
}

二、转换类

package com.example.answer_system.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

//文件转换工具
public class FileUtils {

    /**
     * 将网络文件转换为文件流
     * @param imageUrl
     * @return
     */
    public static MultipartFile fileUrlConvertToMultipartFile(String imageUrl) {
        try {
            // 将在线图片地址转换为URL对象
            URL url = new URL(imageUrl);
            // 打开URL连接
            URLConnection connection = url.openConnection();
            // 转换为HttpURLConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            // 读取输入流中的数据,并保存到字节数组中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            // 将字节数组转换为字节数组
            byte[] bytes = byteArrayOutputStream.toByteArray();
            // 创建ByteArrayInputStream对象,将字节数组传递给它
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            // 创建MultipartFile对象,将ByteArrayInputStream对象作为构造函数的参数
            MultipartFile multipartFile = new MockMultipartFile("file", "filename.jpg", "image/jpg", byteArrayInputStream);
            return multipartFile;
        }catch (IOException ex){
            ex.printStackTrace();
            throw new BusinessException("附件无效");
        }
    }
}

文章来源:https://blog.csdn.net/weixin_41463944/article/details/135433294
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。