Home > other >  How to decode file from base64 in Spring Boot (Java)?
How to decode file from base64 in Spring Boot (Java)?

Time:03-17

I am sending a file from the front-end (Angular) via a web service to the back-end (Java). How to decode the file in Spring Boot?

Here is it my code in Angular: (encode file in base64) in a function with 3 parameters (base64, name, size)

readAndUploadFile(theFile: any) {
    let file = new FileModel();
    
    // Set File Information
    file.fileName = theFile.name;
    file.fileSize = theFile.size;
    file.fileType = theFile.type;
    file.lastModifiedTime = theFile.lastModified;
    file.lastModifiedDate = theFile.lastModifiedDate;
    
    // Use FileReader() object to get file to upload
    // NOTE: FileReader only works with newer browsers
    let reader = new FileReader();
    
    // Setup onl oad event for reader
    reader.onload = () => {
        // Store base64 encoded representation of file
        file.fileAsBase64 = reader.result.toString();
        
        // POST to server
        this.uploadService.uploadFile(file.fileAsBase64,file.fileName,file.fileSize).subscribe(resp => { 
         
            this.messages.push("Upload complete");
            console.log("tst",resp); });
    }
    
    // Read the file
    reader.readAsDataURL(theFile);
} 


uploadFile(): void {
  this.readAndUploadFile(this.theFile);
} 

My code in the back-end:

@RequestMapping("/UploadFile")
public String uploadFile(String base64, String name, String size) throws Exception {
 
    return "true";
}

CodePudding user response:

You can download the file converted to Base64 format using this.

@RequestMapping(value = "/UploadFile")
public String uploadFile(HttpServletResponse response, String base64, String name, String size) throws Exception {
    // If you are using Java 8 or above
    byte[] decodedFile = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename="   name);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    InputStream is = new ByteArrayInputStream(decodedFile);
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
    return "true";
}

CodePudding user response:

byte[] data = Base64.decodeBase64(base64);
try (OutputStream stream = new FileOutputStream("path to file ")) {
    stream.write(data);
}

CodePudding user response:

There are some ways to encode and decode base64, a good way can be with the Apache Commons Codec library or with the Java base64 encoder/decoder. https://www.baeldung.com/java-base64-encode-and-decode

  • Related