[英]Spring Boot optional multipart POST request
我有一項服務,希望通過POST請求有選擇地上傳文件(包括文件將運行單獨的功能)。
我的ReqestMapping
簡化版本如下:
@ApiOperation(value = "Data", nickname = "Create a new data object")
@RequestMapping(value = "/add/{user_id}", produces = "application/json", method = RequestMethod.POST)
public ResponseEntity<Data> addData(@RequestParam("note") String body,
@RequestParam("location") String location,
@RequestParam(value = "file", required = false) List<MultipartFile> file,
@PathVariable String user_id){
if (file != null) {
doSomething(file);
}
doRegularStuff(body, location, user_id);
return new ResponseEntity(HttpStatus.OK);
}
可以看出,我的多部分文件列表中有required = false
選項。 但是,當我嘗試在不包含任何文件的情況下curl
端點並聲明我的內容類型為Content-Type: application/json
,出現錯誤消息,我的請求不是多部分請求。
精細。 因此,我更改為Content-Type: multipart/form-data
並且沒有任何文件,但the request was rejected because no multipart boundary was found
(顯然,因為我沒有文件)。
這使我想知道如何在Spring端點中有一個可選的multipart參數? 我希望避免在我的請求中添加其他參數,例如“ File Attached:True / False”,因為當服務器僅檢查存在性時,這將變得很麻煩且不必要。
謝謝!
您的代碼沒有問題,但是客戶端請求中有問題,因為如果要上傳圖像,Content-Type應該如下所示,
multipart/form-data; boundary="123123"
嘗試刪除Content-Type標頭並進行測試,我將為服務器代碼和客戶端請求放一個示例
服務器代碼:
@RequestMapping(method = RequestMethod.POST, value = "/users/profile")
public ResponseEntity<?> handleFileUpload(@RequestParam("name") String name,
@RequestParam(name="file", required=false) MultipartFile file) {
log.info(" name : {}", name);
if(file!=null)
{
log.info("image : {}", file.getOriginalFilename());
log.info("image content type : {}", file.getContentType());
}
return new ResponseEntity<String>("Uploaded",HttpStatus.OK);
}
使用郵遞員的客戶請求
沒有圖像
卷曲示例:
沒有圖像,具有內容類型
curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "name=test" "http://localhost:8080/api/users/profile"
沒有圖像,沒有內容類型
curl -X POST -F "name=test" "http://localhost:8080/api/users/profile"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.