How to convert a multipart file to File?

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

    You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream():

    public void write(MultipartFile file, Path dir) {
        Path filepath = Paths.get(dir.toString(), file.getOriginalFilename());
    
        try (OutputStream os = Files.newOutputStream(filepath)) {
            os.write(file.getBytes());
        }
    }
    

    You can also use the transferTo method:

    public void multipartFileToFile(
        MultipartFile multipart, 
        Path dir
    ) throws IOException {
        Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
        multipart.transferTo(filepath);
    }
    
    0 讨论(0)
  • 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.

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- setting maximum upload size t 20MB -->
    <property name="maxUploadSize" value="20971520" />
    <!-- max size of file in memory (in bytes) -->
    <property name="maxInMemorySize" value="1048576" />
    <!-- 1MB --> </bean>
    
    0 讨论(0)
  • 2020-11-29 17:27

    if you don't want to use MultipartFile.transferTo(). You can write file like this

        val dir = File(filePackagePath)
        if (!dir.exists()) dir.mkdirs()
    
        val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
            createNewFile()
        }
    
        FileOutputStream(file).use {
            it.write(multipartFile.bytes)
        }
    
    0 讨论(0)
  • 2020-11-29 17:28
      private File convertMultiPartToFile(MultipartFile file ) throws IOException
        {
            File convFile = new File( file.getOriginalFilename() );
            FileOutputStream fos = new FileOutputStream( convFile );
            fos.write( file.getBytes() );
            fos.close();
            return convFile;
        }
    
    0 讨论(0)
  • 2020-11-29 17:31

    You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    

    The source for the MultipartFile save to disk.

    File file = new File(directory, filename);
    
    // Create the file using the touch method of the FileUtils class.
    // FileUtils.touch(file);
    
    // Write bytes from the multipart file to disk.
    FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
    
    0 讨论(0)
  • 2020-11-29 17:33

    small correction on @PetrosTsialiamanis post , new File( multipart.getOriginalFilename()) this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action. System.getProperty("java.io.tmpdir") will create temp directory where your file will be created properly. This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.

    public  static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException {
        File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName);
        multipart.transferTo(convFile);
        return convFile;
    }
    

    put this method in ur common utility and use it like for eg. Utility.multipartToFile(...)

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