vig*_*age 7 spring file-upload http spring-boot angular
我试图使用Angular2和SpringBoot完成我的文件上传功能.我可以证明我的文件上传的java代码工作正常,因为我已经使用Postman成功测试了它.
但是,当从Angular2前端发送文件时,我收到HTTP 400响应说Required request part 'file' is not present
.
这是我从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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我编写了一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
此条件标头附加工作正常.这样做的目的是如果我'Content-Type', 'application/json'
为每个请求添加标头,Spring控制器中的文件上传方法将不接受它.(返回http 415)
一切似乎都很好.但我收到Required request part 'file' is not present
错误回复.这是为什么?我将该参数添加到数据表格中.
let formData: FormData = new FormData();
formData.append('file', photoToSave);
Run Code Online (Sandbox Code Playgroud)
这是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<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);
}
Run Code Online (Sandbox Code Playgroud)
编辑 - 添加浏览器捕获的请求的有效负载
如您所见,那里有param"file".
尝试添加
headers: {
'Content-Type': 'multipart/form-data'
},
Run Code Online (Sandbox Code Playgroud)
给你的
.post(this._endpointUrl + "save-photo", formData)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2927 次 |
最近记录: |