生活随笔
收集整理的這篇文章主要介紹了
File如何转换成MultipartFile
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
MutipartFile是spring里面定義的接口,它封裝了用戶在上傳圖片時所包含的所有信息,但是有些時候我們要將file轉換成MutipartFile,才能在保持原有代碼邏輯的情況下方便代碼的調整,但是file不能直接轉換成MutipartFile,現在就要教大家如何將file轉換成MutipartFile。
如果要轉換,要用到的包是spring-test?
maven:
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>4.2.5.RELEASE</spring.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version><scope>test</scope></dependency></dependencies>
或者
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>4.2.5.RELEASE</spring.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version><scope>test</scope></dependency></dependencies> ?
maven配置好了之后,要用到一個非常重要的類MockMultipartFile?
他是繼承MultipartFile接口來模擬MultipartFile。當然具體的實現要自己看源碼,我們要講的是如何file轉換成MultipartFile。
轉換的方式很簡單,就是創建MockMultipartFile的構造函數。?
具體的有四個構造函數
-MockMultipartFile(String name, byte[] content)?
-MockMultipartFile(String name, InputStream contentStream)?
-MockMultipartFile(String name, String originalFilename, String contentType, byte[] content)?
-MockMultipartFile(String name, String originalFilename, String contentType, InputStream contentStream)?
*name文件名?
*originalFilename原文件名?
*contentStream輸入流?
*content byte數組
例子:?
MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
下面貼上我在應用上面的截取的具體代碼片段:?
要求:把url里的圖片導入到本地。?
WebFileUtils.java
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.springframework.stereotype.Service; @Service("webFileUtils") public class WebFileUtils { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WebFileUtils.class); /** * 根據url拿取file * * @param url * @param suffix * 文件后綴名 * */ public static File createFileByUrl(String url, String suffix) { byte[] byteFile = getImageFromNetByUrl(url); if (byteFile != null) { File file = getFileFromBytes(byteFile, suffix); return file; } else { logger.info("生成文件失敗!"); return null; } } /** * 根據地址獲得數據的字節流 * * @param strUrl * 網絡連接地址 * @return */ private static byte[] getImageFromNetByUrl(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片數據 byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數據 return btImg; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 從輸入流中獲取數據 * * @param inStream * 輸入流 * @return * @throws Exception */ private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } // 創建臨時文件 private static File getFileFromBytes(byte[] b, String suffix) { BufferedOutputStream stream = null; File file = null; try { file = File.createTempFile("pattern", "." + suffix); System.out.println("臨時文件位置:"+file.getCanonicalPath()); FileOutputStream fstream = new FileOutputStream(file); stream = new BufferedOutputStream(fstream); stream.write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; } public static void main(String[] args) { WebFileUtils.createFileByUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1508327007250&di=b7be3e44999983ec75ba54537287ff13&imgtype=0&src=http%3A%2F%2Fb.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Faa64034f78f0f736ce4ff5720055b319ebc4130b.jpg","jpg"); } }
?
ImgUploadServiceImpl.java
public MultipartFile createImg(String url){try {// File轉換成MutipartFileFile file = WebFileUtils.createFileByUrl(url, "jpg");FileInputStream inputStream = new FileInputStream(file);MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);//注意這里面填啥,MultipartFile里面對應的參數就有啥,比如我只填了name,則//MultipartFile.getName()只能拿到name參數,但是originalFilename是空。return multipartFile; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } 以上是我做項目中對file轉MultipartFile的分享。?
api鏈接:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/mock/web/MockMultipartFile.html
轉載于:https://www.cnblogs.com/powerwu/articles/9039538.html
總結
以上是生活随笔為你收集整理的File如何转换成MultipartFile的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。