How to convert a multipart file to File?

后端 未结 9 1993
有刺的猬
有刺的猬 2020-11-29 16:44

Can any one tell me what is a the best way to convert a multipart file (org.springframework.web.multipart.MultipartFile) to File (java.io.File) ?

In my spring mvc w

9条回答
  •  孤独总比滥情好
    2020-11-29 17:27

    The answer by Alex78191 has worked for me.

    public File getTempFile(MultipartFile multipartFile)
    {
    
    CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
    FileItem fileItem = commonsMultipartFile.getFileItem();
    DiskFileItem diskFileItem = (DiskFileItem) fileItem;
    String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
    File file = new File(absPath);
    
    //trick to implicitly save on disk small files (<10240 bytes by default)
    
    if (!file.exists()) {
        file.createNewFile();
        multipartFile.transferTo(file);
    }
    
    return file;
    }
    

    For uploading files having size greater than 10240 bytes please change the maxInMemorySize in multipartResolver to 1MB.

    
    
    
    
    
     
    

提交回复
热议问题