Issue
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 onload 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";
}
Solution
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";
}
Answered By - Fati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.