I have a problem. I want to convert BufferedImage
to the MultipartFile.
First, on my UI I sent base64
to the server, and on my server, I convert to the BufferedImage
after that I want to convert BufferedImage to the
MultipartFile and save on the local storage.
This is my method:
@PostMapping("/saveCategory")
@ResponseStatus(HttpStatus.OK)
public void createCategory(@RequestBody String category ) {
BufferedImage image = null;
OutputStream stream;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(category);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = fileStorageService.storeFile(image );
My storage method:
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if (fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
System.out.println(ex);
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}