我有一个问题。我想将
BufferedImage
转换为 MultipartFile
。
首先,在我的 UI 上,我将 base64
字符串发送到服务器,然后在我的服务器上,我将其转换为 BufferedImage
。之后,我想将 BufferedImage 转换为 MultipartFile 并将其保存在本地存储上。
这是我的控制器方法:
@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);
我的储存方法:
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);
}
}
从
base64
到MultipartFile
的这种转换是由Spring自动完成的。您只需要使用正确的注释即可。
您可以创建一个包装器
dto
类来保存所有必要的数据。
public class FileUploadDto {
private String category;
private MultipartFile file;
// [...] more fields, getters and setters
}
然后你可以在你的控制器中使用这个类:
@RestController
@RequestMapping("/upload")
public class UploadController {
private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
@PostMapping
public void uploadFile(@ModelAttribute FileUploadDto fileUploadDto) {
logger.info("File upladed, category= {}, fileSize = {} bytes", fileUploadDto.getCategory(), fileUploadDto.getFile().getSize());
}
}
我第一眼没明白问题重点的原因是
@RequestBody String category
。我认为这是一个非常非常具有误导性的file变量名称。不过,我还创建了带有类别字段的 DTO 类,以便您可以将其包含在您的请求中。
当然,然后您就可以摆脱控制器逻辑,只需调用
fileStorageService.storeFile(fileUploadDto.getFile());
之类的服务方法或传递整个文件并使用category
字段。
我还包括从 Postman 发送的请求和一些控制台输出: