10

我想用 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但不工作且没有解决方案。

4

2 回答 2

17
    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 对象获取多部分文件的另一种方法

于 2015-06-02T05:30:11.100 回答
5
    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。

于 2013-12-13T17:05:54.890 回答