1
我試圖將圖像發送到我的REST web服務,但出現錯誤。 我嘗試了很多不同的方法(保存字節數組,發送另一種類型的文件,...),但沒有找到好的方法。將多部分文件發送到REST api時發生錯誤
春季服務代碼(調用帶參數的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,然後能夠保存它呢?
Ohhhh謝謝你!你救了我的一天;) –
歡迎!任何時間男士。很高興幫助你。 – Deepanjan