我试图使用Angular2和SpringBoot完成我的文件上传功能.我可以证明我的文件上传的java代码工作正常,因为我已经使用Postman成功测试了它.
但是,当从Angular2前端发送文件时,我收到HTTP 400响应说不存在所需的请求部分’文件’.
这是我从Angular2发送POST请求的方式.
savePhoto(photoToSave: File) {
let formData: FormData = new FormData();
formData.append('file',photoToSave);
// this will be used to add headers to the requests conditionally later using Custom Request Options
this._globals.setRequestFrom("save-photo");
let savedPath = this._http
.post(this._endpointUrl + "save-photo",formData)
.map(
res => {
return res.json();
}
)
.catch(handleError);
return savedPath;
}
请注意,我编写了一个CustomRequestOptions类,它扩展了BaseRequestOptions以附加Authorization标头和Content Type标头.内容类型标题将有条件地添加.
以下是代码.
@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
constructor(private _globals: Globals) {
super();
this.headers.set('X-Requested-By','Angular 2');
this.headers.append('virglk',"vigamage");
}
merge(options?: RequestOptionsArgs): RequestOptions {
var newOptions = super.merge(options);
let hdr = this._globals.getAuthorization();
newOptions.headers.set("Authorization",hdr);
if(this._globals.getRequestFrom() != "save-photo"){
newOptions.headers.set('Content-Type','application/json');
}else{
//request coming from save photo
console.log("request coming from save photo");
}
return newOptions;
}
}
此条件标头附加工作正常.这样做的目的是,如果我为每个请求添加’Content-Type’,’application / json’标头,Spring控制器中的文件上传方法将不接受它. (返回http 415)
一切似乎都很好.但我得到必需的请求部分’文件’不存在错误响应.这是为什么?我将该参数添加到数据表格中.
let formData: FormData = new FormData();
formData.append('file',photoToSave);
这是Spring Controller方法供您参考.
@RequestMapping(method = RequestMethod.POST,value = "/tender/save-new/save-photo",consumes = {"multipart/form-data"})
public ResponseEntity> uploadPhoto(@RequestParam("file") MultipartFile file){
if (file.isEmpty()) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage("DEBUG: Attached file is empty");
return new ResponseEntity
如您所见,那里有param“file”.
最佳答案
尝试添加
headers: {
'Content-Type': 'multipart/form-data'
},
到你的
.post(this._endpointUrl + "save-photo",formData)