我有上传图片的帖子请求如下:
@RequestMapping(method = RequestMethod.POST, value = BASE_PATH)
public ResponseEntity<?> createFile(@RequestParam("file") MultipartFile file, HttpServletRequest servletRequest){
URI localUri = null;
try{
imageService.createImage(file);
final URI localhostUri = new URI(servletRequest.getRequestURL().toString() + "/")
.resolve(file.getOriginalFilename() + "/raw");
localUri = localhostUri;
}catch (IOException e){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Could not upload " + file.getOriginalFilename() + "=>" + e.getMessage());
}catch (URISyntaxException e) {
e.printStackTrace();
}
return ResponseEntity.created(localUri)
.body("Successfully Uploaded " + file.getOriginalFilename());
}
以下是一次获取图像的GET方法:
@RequestMapping(method = RequestMethod.GET, value = BASE_PATH + "/" + FILENAME + "/raw")
@ResponseBody
public ResponseEntity<?> oneRawImage(@PathVariable String filename){
try{
Resource file = imageService.findOneImage(filename);
return ResponseEntity.ok()
.contentLength(file.contentLength())
.contentType(MediaType.IMAGE_JPEG)
.body(new InputStreamResource(file.getInputStream()));
}catch (IOException e){
return ResponseEntity.badRequest()
.body("Couldn't Find" + filename + "=>" + e.getMessage());
}
}
当我执行POST时,我得到一个正确的响应,说明文件已上传(我不确定它是否是,因为返回请求不在try块中。以下是我得到的响应:
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> POST /images HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.49.0
> Accept: */*
> Content-Length: 69927
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------
b5f1ef58e19bbb8d
>
< HTTP/1.1 100
< HTTP/1.1 201
< Location: http://localhost:8080/images/image2.jpg/raw
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 32
< Date: Wed, 14 Jun 2017 18:24:06 GMT
<
* Connection #0 to host localhost left intact
Successfully Uploaded image2.jpg
但是当我尝试执行GET请求以获取我发布的图像时,我收到以下错误:
Couldn't Findimage2.jpg=>ServletContext resource [/fileupload-dir/image2.jpg] cannot be resolved to URL because it does not exist
我尝试了多种方式的调试,但没有成功。任何springers的帮助将不胜感激!感谢
答案 0 :(得分:0)
所以我意识到这个问题非常琐碎。被调用的服务方法:
public Resource findOneImage(String filename){
return resourceLoader.getResource("file:" + UPLOAD_ROOT + "/" + filename);
}
'文件'中缺少冒号。因此,resourceLoader没有被解析为正确的URL。