简体   繁体   中英

Spring error when sending multipartfile to REST api

I'm trying to send an image to my REST webservice but I get an error. I tried a lot of different ways (save the bytes array, send another type of file, ...) but don't find the good way.

Spring service code (call the API with parameters):

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 code :

@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.";
    }
}

Does anyone have a solution to send my file to my API and then be able to save it ?

Instead of handling files using MultiPartFile you can convert the file to Base64 string and store with the help of annotation using @Lob. You can use the FileReader Object to read the file while sending it to the REST Web service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM