2016-09-17 154 views
0

我是新來的spring rest,並試圖創建一個REST POST API,用戶可以在其中發送文件到服務器。spring-boot REST POST API發送文件

@RequestMapping(value = "/order", method = RequestMethod.POST) 
public String create(@RequestParam("file") MultipartFile file) {   
     System.out.println("---------INSIDE ORDER----------"); 
     return "file succesfully received!"; 
} 

但是當我通過上傳將Order.txt文件並選擇表單數據(郵遞員)對這個API的調用我得到這個錯誤

{ 
    "timestamp": 1474129488458, 
    "status": 400, 
    "error": "Bad Request", 
    "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException", 
    "message": "Required request part 'file' is not present", 
    "path": "/order" 
} 
+0

你是怎麼傳遞'file'參數的?請發佈請求。 – Maroun

+0

curl -X POST http:// localhost:8080/order \ -d json ='{「name」:「john」,「lastNane」:「doe」}' – krs8888

+0

如果我想要附加一個requestBody文本文件(其中包含JSON) – krs8888

回答

1

問題不在於你的代碼接受請求。這與你的要求是如何做的。

-d用於傳遞數據。你必須使用-F如下圖所示

curl -X POST localhost:8080/order -F "[email protected]" 

參考的curl manual後部分獲取更多細節

+0

感謝此作品 – krs8888

+0

酷...開心編碼:) –

-1

驗證,如果你有這些項目:

@Bean 
public CommonsMultipartResolver multipartResolver() { 
    CommonsMultipartResolver multipart = new CommonsMultipartResolver(); 
    multipart.setMaxUploadSize(3 * 1024 * 1024); 
    return multipart; 
} 

@Bean 
@Order(0) 
public MultipartFilter multipartFilter() { 
    MultipartFilter multipartFilter = new MultipartFilter(); 
    multipartFilter.setMultipartResolverBeanName("multipartResolver"); 
    return multipartFilter; 
} 

而在pplications.properties

# MULTIPART (MultipartProperties) 
spring.http.multipart.enabled=true 
# Enable support of multi-part uploads. 
# spring.http.multipart.file-size-threshold=3 # Threshold after which files will be written to disk. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.location=/
# Intermediate location of uploaded files. 
spring.http.multipart.max-file-size=10MB 
# Max file size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.max-request-size=10MB 
# Max request size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.resolve-lazily=false 
# Whether to resolve the multipart request lazily at the time of file or parameter access.`enter code here`