Home > OS >  How to convert List<MultipartFile> files in base 64 in Spring boot?
How to convert List<MultipartFile> files in base 64 in Spring boot?

Time:11-05

I need to convert file in base64. At the moment it saves the files well but not in base 64

My code in Controller is:

@PostMapping("/upload")
public ResponseEntity <Response> uploadFiles(@RequestParam("files") 
 List <MultipartFile> files) throws Exception { 

    fileServiceAPI.save(files);
    return ResponseEntity.status(HttpStatus.OK)
            .body(new Response("The files were successfully uploaded to the server"));

}

My code in service:

private final Path rootFolder = 
Paths.get("upload");

@Override
public void save(MultipartFile file) throws Exception {
    Files.copy(file.getInputStream(), this.rootFolder.resolve(file.getOriginalFilename()));
}

@Override
public void save(List<MultipartFile> files) throws Exception {
    
    
    for(MultipartFile file: files){
        
        this.save(file);
    }
}

CodePudding user response:

You can use Apache Commons IO library to do this, https://mvnrepository.com/artifact/commons-io/commons-io

you can encode the input stream from your file.getInputStream()

Check below code,

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;

public class EncodeExample {

    public static void main(String[] args) {

        try {
            String string = "file content";
            InputStream source = new ByteArrayInputStream(string.getBytes());
            byte[] sourceBytes = IOUtils.toByteArray(source);
            String encodedString = Base64.getEncoder().encodeToString(sourceBytes);

            System.out.println("encoded: "   encodedString);


            byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
            String decodedString = new String(decodedBytes);
            System.out.println("decoded: "   decodedString);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Output:

encoded: ZmlsZSBjb250ZW50

decoded: file content

CodePudding user response:

You can use Base64.encodeBase64 to convert MultipartFile to byte[], then new ByteArrayInputStream like so:

@Override
public void save(MultipartFile file) throws Exception {
    byte[] base64 = Base64.encodeBase64(file.getBytes());
    Files.copy(new ByteArrayInputStream(base64), this.rootFolder.resolve(file.getOriginalFilename()));
}
  • Related