如何在Java中将Base64转换为MultipartFile

3

我有一个问题。我想将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);

        }
    }

怎么了?为什么你的MultipartFile参数被注释掉了? - undefined
我更新了帖子。问题是我无法将BufferedImage保存为MultipartFile,我必须找到一种将我的BufferedImage转换为MultipartFile的方法。 - undefined
请参考这个链接:https://dev59.com/Zmgv5IYBdhLWcg3wF9BP - undefined
谢谢,但我想将base64文件转换为MultipartFile。这可行吗? - undefined
好的,我终于明白问题所在了,马上会发布一个答案。 - undefined
1个回答

9
这样从 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。我认为这对于一个 文件 来说是一个非常误导性的变量名。然而,我创建了带有类别字段的 DTO 类,以便您可以在请求中包含它。
当然,然后您可以摆脱控制器逻辑,只需调用服务方法,如 fileStorageService.storeFile(fileUploadDto.getFile()); 或传递整个文件并利用 category 字段。

编辑

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

Postman 请求和控制台输出


我有另一个问题,因为我想要像JSON对象一样发送类别、文件和产品,并绑定到我的模型中。我认为无法将对象与MultipartFile一起发送,对吗? - undefined
当然可以,在你的DTO类中可以添加任意多个字段。 - undefined
是枚举(ENUM)还是普通的POJO类?如果是枚举,应该没有任何问题,如果是类的话,我觉得你可能需要另外解决一下。 - undefined
这是我的CategoryModel类:@Entity @Table(name = "Category") @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" }) public class CategoryModel { @Id @Column(name = "id") //@GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String category_name; private String category_description; private String image_path; @JsonIgnore @OneToMany(mappedBy = "category") private Set category; }使用这个模型是可能的。 - undefined
你可以根据你的DTO创建相应的字段,然后将它们映射到你的实体类中。 - undefined
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接