java.lang.NullPointerException while creating DiskFileItem

前端 未结 5 1589
我寻月下人不归
我寻月下人不归 2021-01-13 04:14

I am trying to write a unit test for handling a file upload controller using Spring 3. Now if I send the image over to my service method through the controller everything wo

相关标签:
5条回答
  • 2021-01-13 04:55

    Although not entirely related to the question. I ran into the same exception when deploying some file-upload code to GAE. I modified systempuntoout's code from here using apache fileupload on GAE (which uses the streams part of apache commons) which then worked fine.

    0 讨论(0)
  • 2021-01-13 05:03

    What does this part of this log say?

    log.info("found file: " +file.exists());
    log.info("file size: " +file.length());
    

    But I think the problem might be because of this:

    File file = new File("//Users//test//Downloads//");
    

    It looks like it's pointing to a directory instead of a file, so maybe that is why you are getting a NullPointerException when you want to get the size of DiskFileItem

    0 讨论(0)
  • 2021-01-13 05:10

    And if none of the solutions above work for you as it happened for me :) simply ditch the DiskFileItem and use the solution bellow:

      final File fileToUpload = new File("src/test/resources/files/test.txt");
      final MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>();
      request.add("file", new FileSystemResource(fileToUpload.getAbsolutePath()));
    
    0 讨论(0)
  • 2021-01-13 05:10
    new DiskFileItem(fieldName, contentType, isFormField, fileName, sizeThreshold, file);
    

    results in a null value. Look into the docs to see what's wrong or maybe you pass some null as parameters

    0 讨论(0)
  • 2021-01-13 05:11

    I ran into the same problem. The issue is that DiskFileItem.getSize() is temporally coupled with DiskFileItem.getOutputStream() in that an internal field is initialized in getOutputStream and used in getSize.

    The solution is to do

    final File TEST_FILE = new File("src/test/resources/test.jpg");
    final DiskFileItem diskFileItem = new DiskFileItem("file", "image/jpeg", true, TEST_FILE.getName(), 100000000, TEST_FILE.getParentFile());
    diskFileItem.getOutputStream();
    

    before passing diskFileItem to the constructor of CommonsMultipartFile.

    0 讨论(0)
提交回复
热议问题