java中如何将base64转换为MultipartFile

SIn*_*sun 3 base64 spring-boot

我有个问题。我想转换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 );
Run Code Online (Sandbox Code Playgroud)

我的存储方法:

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);

        }
    }
Run Code Online (Sandbox Code Playgroud)

Pij*_*rek 9

base64这种从到 的转换MultipartFile是由 Spring 自动完成的。您只需要使用正确的注释即可。

您可以创建一个dto包含所有必要数据的包装类。

public class FileUploadDto {
    private String category;
    private MultipartFile file;
    // [...] more fields, getters and setters
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的控制器中使用这个类:

@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());
    }

}
Run Code Online (Sandbox Code Playgroud)

我第一眼没有明白问题的要点的原因是@RequestBody String category。我认为这是一个非常非常具有误导性的文件变量名。不过,我还创建了带有类别字段的 DTO 类,以便您可以将其包含在您的请求中。

当然,然后您就可以摆脱控制器逻辑,只需调用服务方法fileStorageService.storeFile(fileUploadDto.getFile());或传递整个文件并使用category字段即可。

编辑

我还包括从 Postman 发送的请求和一些控制台输出:

邮递员请求和控制台输出