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;
	}

}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280275.html

(0)
上一篇 2022年8月13日
下一篇 2022年8月13日

相关推荐

发表回复

登录后才能评论