将文件转换为MultiPartFile

有没有办法将File对象转换为MultiPartFile? 这样我就可以将该对象发送给接受MultiPartFile接口对象的方法?

 File myFile = new File("/path/to/the/file.txt") MultiPartFile ....? def (MultiPartFile file) { def is = new BufferedInputStream(file.getInputStream()) //do something interesting with the stream } 

MockMultipartFile就是为此而存在的。 如在文件路径已知的情况下,在您的代码段中,以下代码适用于我。

 import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.mock.web.MockMultipartFile; Path path = Paths.get("/path/to/the/file.txt"); String name = "file.txt"; String originalFileName = "file.txt"; String contentType = "text/plain"; byte[] content = null; try { content = Files.readAllBytes(path); } catch (final IOException e) { } MultipartFile result = new MockMultipartFile(name, originalFileName, contentType, content); 
  File file = new File("src/test/resources/input.txt"); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); 
 MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx"))); 

这段代码对我来说很好。也许你可以尝试一下。

  File file = new File("src/test/resources/validation.txt"); DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile()); fileItem.getOutputStream(); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); 

你需要的

  fileItem.getOutputStream(); 

因为否则会抛出NPE。

在我的情况下,

 fileItem.getOutputStream(); 

没用。 因此我自己使用IOUtils ,

 File file = new File("/path/to/file"); FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile()); try { InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream(); IOUtils.copy(input, os); // Or faster.. // IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream()); } catch (IOException ex) { // do something. } MultipartFile multipartFile = new CommonsMultipartFile(fileItem);