我需要將照片上傳到使用Spring Boot編寫的服務器。對於發送請求的前端,我使用Angular2。使用Angular2發送MultipartFile作爲請求參數給REST服務器
這是我接受HTTP請求的API。它工作正常。 (我用郵差測試過)
@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo")
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){
if (file.isEmpty()) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("DEBUG: Attached file is empty");
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
}
String returnPath = null;
try {
// upload stuff
} catch (IOException e) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(e.getMessage());
return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>(returnPath, HttpStatus.OK);
}
我不知道該如何在Angular2中編寫代碼來調用服務器。 以下是我想出的。
savePhoto(photoToSave: File) {
let formData: FormData = new FormData();
formData.append('file', photoToSave);
let savedPath = this._http
.post(this._endpointUrl + "tender/save-new/save-photo", formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
return savedPath;
}
正如你所看到的,我在發送之前追加'file'
參數表單數據。服務器方法接受RequestParam
作爲'file'
。
但是,在服務器日誌中,我收到以下錯誤。
org.springframework.web.multipart.MultipartException:當前請求 不在 org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)多部分請求
請注意,由於SprinBoot隱式處理它,因此我沒有聲明CommonsMultipartResolver
bean。 (我聽說過,如果我錯了,請糾正)
我認爲由於請求中缺少值而出現錯誤。春天在說什麼handleMissingValue
?我錯過了什麼?
但根據以下的答案,Angular2最終支持文件上傳,而不XHR https://stackoverflow.com/a/39862337/3892439 – vigamage
嗯這很有意思。 ,不知道它是否受支持,您是否在解決方案的第二部分中將消耗= {「multipart/form-data」}放入您的請求映射中? –
是的。現在它給了我「否」Access-Control-Allow-Origin'標題出現在請求的資源上。原因'http:// localhost:3000'因此不被允許訪問。 ''。但事情是我已經把'@CrossOrigin(origins =「http:// localhost:3000」)'在我的控制器 – vigamage