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 对象

转载于:https://www.cnblogs.com/youyouxiaosheng-lh/p/11026763.html

你可能感兴趣的:(java中文件上传下载将file转为MultipartFile)