java中文件上傳下載將file轉為MultipartFile


file轉MultipartFile簡單的方式:

  File file = new File("PATH");

  FileInputStream fileInputStream = new FileInputStream(file);

  MultipartFile multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),

  ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

 

但是上面的方式需要導入spring-test下的包, 因為maven中沒有引入此坐標,所以我使用了下面的方式:

將 file轉MultipartFile:

FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
FileItem item = factory.createItem(textFieldName, "text/plain", true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(savePath+fileName);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
MultipartFile multipartFile = new CommonsMultipartFile(item);

這樣我們就獲取到了一個 MultipartFile 對象


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM