How to convert a multipart file to File?

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

    MultipartFile.transferTo(File) is nice, but don't forget to clean the temp file after all.

    // ask JVM to ask operating system to create temp file
    File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_POSTFIX);
    
    // ask JVM to delete it upon JVM exit if you forgot / can't delete due exception
    tempFile.deleteOnExit();
    
    // transfer MultipartFile to File
    multipartFile.transferTo(tempFile);
    
    // do business logic here
    result = businessLogic(tempFile);
    
    // tidy up
    tempFile.delete();
    

    Check out Razzlero's comment about File.deleteOnExit() executed upon JVM exit (which may be extremely rare) details below.

提交回复
热议问题