在我的angular4应用程序中,我尝试将视频上传到服务器。 但无论我添加到内容类型,它总是会导致服务器出错。 在角度1中,使用 {' Content-Type&#39 ;: undefined}
来命中相同的api我尝试了相同的角度,但它的工作。 数据和一切都是正确的。 我试过内容类型设置如下
headers.append('Content-Type', 'multipart/form-data');
headers.append('Authorization', token);
headers.set('Accept', 'application/json');
以及
headers.append(' Content-Type',undefined);
下面是http请求方法:
public uploadVideo(formData: any) {
var Upload = this.baseUrl + this.ngAuth.getApiUrl('Upload');
var authData = JSON.parse(this.localStorage.localStorageGet('token'));
var token = 'Bearer ' + authData.token;
var self = this;
var headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Authorization', token);
headers.set('Accept', 'application/json');
return this.http.post(Upload , formData, { headers: headers, method: 'POST' })
.map((res: Response) => res.json());
}
请指导! 感谢
答案 0 :(得分:18)
因此,经过大量的解决方案,我偶然发现了issue
它表示不要将Content-Type添加到标题中。 所以从我的请求标题中我删除了
headers.append('Content-Type', 'multipart/form-data');
谢谢!
答案 1 :(得分:3)
我将为Angular 6和Spring Boot提供参考。
角度6:
onSubmit(){
const formdata: FormData = new FormData();
console.log(this.currentFileUpload)
formdata.append('uploadedFile', this.currentFileUpload);
formdata.append('description',"My Desc");
formdata.append('companyName',"ABC")
formdata.append('numberOfRecords',"2")
console.log(formdata.get('uploadedFile'))
this.asyncService.makeUploadRequest('file/upload',formdata).subscribe(response => {
console.log(response)
if(response.responseCode == '00'){
console.log('Successfully uploaded')
}
else {
console.log("error")
}
});
}
makeUploadRequest(method, body) : Observable<any> {
const url = "http://localhost:8097" + "/" + method;
const headers = new Headers();
this.token="Bearer"+" "+localStorage.getItem('token');
headers.append('Authorization', this.token);
// No need to set 'content type'
const options = new RequestOptions({headers: headers});
return this.http.post(url, body, options).pipe(
map((response : Response) => {
var json = response.json();
return json;
})
);
}
Spring Boot API:
@RestController
@RequestMapping(value = { "/file" })
public class FileController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Response uploadFile(@RequestParam("uploadedFile") MultipartFile uploadedFileRef){
System.out.println(uploadedFileRef);
}
}