Multipart transferTo looks for a wrong file address when using createTempFile

后端 未结 3 912
灰色年华
灰色年华 2021-01-22 01:04

I have the following java code in Spring framework to convert a multipart file to a regular file:

    public static File convertToFile(MultipartFile multipart) {         


        
相关标签:
3条回答
  • 2021-01-22 01:06

    I solved the same issue by adding apache Commons FileUpload component. Hope it helps for you.

    1. add pom dependency
        <!-- File Upload -->
        <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
        </dependency>
    
    1. add resolver to spring mvc configuration
        @Bean(name = "multipartResolver")
        public CommonsMultipartResolver multipartResolver() {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
            multipartResolver.setMaxUploadSize(100000);
            return multipartResolver;
        }
    
    0 讨论(0)
  • 2021-01-22 01:17

    I figured out what I was doing wrong.

    I was trying to convert MultipartFile to File outside of the service layer (in another component). Now I do this conversion inside the service layer (but in a separate class) and it's working fine.

    0 讨论(0)
  • 2021-01-22 01:25

    So the code looks like this: StandardMultipartHttpServletRequest

    public void transferTo(File dest) throws IOException, IllegalStateException {
      this.part.write(dest.getPath());
    }
    

    and MultiPartInputStreamParser:

        /**
         * @see javax.servlet.http.Part#write(java.lang.String)
         */
        public void write(String fileName) throws IOException
        {
            if (_file == null)
            {
                _temporary = false;
    
                //part data is only in the ByteArrayOutputStream and never been written to disk
                _file = new File (_tmpDir, fileName);
    

    So in the case that the file isn't on disk, we will end up with /tmp twice.

    I think this is a bug in StandardMultipartHttpServletRequest -- it is passing a path to something which expects a filename.

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