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(转)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南