我想用Spring将File转换为multipartfile。我做了这个:
File in;
MultipartFile file = null;
in = new File("C:...file on disk");
int size = (int) in.length();
DiskFileItem fileItem = new DiskFileItem("file", "application/vnd.ms-excel", false, nomefile, size ,in.getAbsoluteFile());
file = new CommonsMultipartFile(fileItem);
但收到此例外:
threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.commons.fileupload.disk.DiskFileItem.getSize(DiskFileItem.java:316)
我认为fileItem为null但是在填充调试模式时,还有另一种解决方案吗? 我有这篇文章Converting File to MultiPartFile但没有工作,没有解决方案。
答案 0 :(得分:13)
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));
这是从File对象
获取多部分文件的另一种方法答案 1 :(得分:3)
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。