How to convert a multipart file to File? How to convert a multipart file to File? java java

How to convert a multipart file to File?


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


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(...)


Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());

Where multipartFile is your org.springframework.web.multipart.MultipartFile.