2017-06-14 134 views
0

我上傳圖片我的職務的請求返回400如下:春季啓動GET請求圖像

@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 

我試圖以多種方式調試,但沒有成功。任何來自斯普林格的幫助將不勝感激!謝謝

+1

是'/ fileupload-dir /'映射是否正確?我無法從提供的代碼中看出 - 您的方法似乎已映射到'../ raw' – ochi

+0

@ochi這很有趣,在findOneImage Service方法中,我實際上在resourceLoader.getResource(「file:」+ UPLOAD_ROOT +「/」+文件名)。我並不完全理解':'的用法,但那是問題所在。 – Omkar

+1

您的問題標題是誤導...標題說,你得到一個404(資源未找到),但真的你得到一個400(壞請求) - 現在我們知道爲什麼... – ochi

回答

0

所以我意識到這個問題是一個非常卑鄙的問題。正在調用的服務方法:

public Resource findOneImage(String filename){ 
    return resourceLoader.getResource("file:" + UPLOAD_ROOT + "/" + filename); 
} 

「文件」中冒號缺失。因此,resourceLoader沒有得到解決到一個正確的網址。