url图片转MultipartFile(转)

2022/8/13 23:24:34

本文主要是介绍url图片转MultipartFile(转),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class FileUtils {

	// 通过Url将图片转为MultipartFile
	public static MultipartFile uploadImgUrlToMultipartFile(String url) {
		byte[] bytes = downloadPicture(url);
		String name = "imageFile" + url.substring(url.lastIndexOf("."));
		MultipartFile multipartFile = getMultipartFile(name, bytes);
		return multipartFile;
	}

	// 获取图片二进制
	private static byte[] downloadPicture(String url) {
		URL urlConnection = null;
		HttpURLConnection httpURLConnection = null;
		try {
			urlConnection = new URL(url);
			httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
			InputStream in = httpURLConnection.getInputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			in.close();
			out.close();
			return out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpURLConnection.disconnect();
		}
		return null;
	}

	// 二进制文件转换MultipartFile
	public static MultipartFile getMultipartFile(String name, byte[] bytes) {
		MultipartFile mfile = null;
		ByteArrayInputStream in = null;
		try {
			in = new ByteArrayInputStream(bytes);
			FileItemFactory factory = new DiskFileItemFactory(16, null);
			FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
			IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
			mfile = new CommonsMultipartFile(fileItem);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return mfile;
	}

}

 



这篇关于url图片转MultipartFile(转)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程