Spring 将多部分文件发送到 REST 时出错 api

Spring error when sending multipartfile to REST api

我正在尝试将图像发送到我的 REST 网络服务,但出现错误。 我尝试了很多不同的方法(保存字节数组,发送另一种类型的文件,...)但没有找到好的方法。

Spring服务代码(调用API带参数):

public void uploadImage(String id, MultipartFile file) {
    RestTemplate rt = new RestTemplate();
    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("filename", "tt");
    map.add("extension", "png");
    map.add("file", file);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
            map, headers);
    ResponseEntity<String> result = rt.exchange(WebConstant.API_URL + "melt/" + id + "/image", HttpMethod.POST, requestEntity, String.class);
}

API代码:

@RequestMapping(value="/{meltId}/image", method=RequestMethod.POST)
public @ResponseBody String uploadMeltImage(@PathVariable String meltId, @RequestParam String filename, @RequestParam String extension, @RequestParam("file") MultipartFile file){
    System.out.println("check 1");
    Melt knownMelt = meltRepo.findOne(meltId);
    if (file != null && knownMelt != null && extension != null && filename != null) {
        try {
            String url = filename + "." + extension;
            InputStream is = file.getInputStream();

            // Prepare buffered image.
            BufferedImage img = ImageIO.read(is);

            // Create a byte array output stream.
            ByteArrayOutputStream bao = new ByteArrayOutputStream();

            // Write to output stream
            ImageIO.write(img, extension, bao);

            if (knownMelt.getImageUrl() != url){
                knownMelt.setImageUrl(url);
                meltRepo.save(knownMelt);
            }
            return "You successfully uploaded for melt" + meltId + "!";

        } catch (Exception e) {
            return "You failed to upload for melt" + meltId + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload for melt" + meltId + " because the file was empty.";
    }
}

有没有人有办法将我的文件发送到我的 API 然后能够保存它?

除了使用 MultiPartFile 处理文件外,您还可以将文件转换为 Base64 字符串并使用 @Lob 借助注释进行存储。您可以使用 FileReader 对象在将文件发送到 REST Web 服务时读取文件。