将multipartfile发送到REST API时出现Spring错误

时间:2016-06-13 17:13:03

标签: java spring rest upload multipart

我试图将图像发送到我的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,然后才能保存?

1 个答案:

答案 0 :(得分:0)

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