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

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

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("附件无效");
        }
    }
}

你可能感兴趣的:(java,开发语言)