How to convert a multipart file to File?

后端 未结 9 1981
有刺的猬
有刺的猬 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:33

    You can access tempfile in Spring by casting if the class of interface MultipartFile is CommonsMultipartFile.

    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;
    }
    

    To get rid of the trick with files less than 10240 bytes maxInMemorySize property can be set to 0 in @Configuration @EnableWebMvc class. After that, all uploaded files will be stored on disk.

    @Bean(name = "multipartResolver")
        public CommonsMultipartResolver createMultipartResolver() {
            CommonsMultipartResolver resolver = new CommonsMultipartResolver();
            resolver.setDefaultEncoding("utf-8");
            resolver.setMaxInMemorySize(0);
            return resolver;
        }
    

提交回复
热议问题