How to convert a multipart file to File?

后端 未结 9 1968
有刺的猬
有刺的猬 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);
    }
    

提交回复
热议问题