java file upload and download the file into MultipartFile

file transfer MultipartFile simple way:

  File file = new File("PATH");

  FileInputStream fileInputStream = new FileInputStream(file);

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

  ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

 

However, the above method requires the introduction of packet spring-test, since this coordinate without introducing maven, I used the following way:

The file transfer 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);

So we get to a target MultipartFile

Guess you like

Origin www.cnblogs.com/youyouxiaosheng-lh/p/11026763.html