[英]Cannot send formdata using post request
I'm trying to send a form data with a file using POST request in Angular 4. If the header is 'Content-Type': 'application/json'
the form data does not send to the server. 我正在尝试使用Angular 4中的POST请求通过文件发送表单数据。如果标头是'Content-Type': 'application/json'
则表单数据不会发送到服务器。 If the header is 'Content-Type': 'multipart/form-data'
, the client side can send the form data to the server. 如果标题是'Content-Type': 'multipart/form-data'
,则客户端可以将表单数据发送到服务器。 But in postman application/json will work. 但是在邮递员中,application / json可以工作。 I want the same in Angular 4. 我想要在Angular 4中也一样。
Component.ts: ` Component.ts:
let formData: FormData = new FormData();
formData.append("courseId", this.course_id.toString());
formData.append("courseName", this.course_name.toString());
formData.append('pic', this.file);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers,withCredentials: true });
this.http.post('http://localhost:3000/createNew', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)`
Html: HTML:
<input type="file" name="pic" (change)="onFileChange($event)">
<input type="button" value="Upload" (click)="onUpload()">
To submit formdata
in angular or anywhere, the content type of the should not be a Json
. 要以角度或任何位置提交formdata
,的内容类型不应为Json
。 So you can do like this : 所以你可以这样:
let formData: FormData = new FormData();
formData.append("courseId", this.course_id.toString());
formData.append("courseName", this.course_name.toString());
formData.append('pic', this.file);
let headers = new Headers({ 'Content-Type': 'multipart/form-data' });
let options = new RequestOptions({ headers: headers,withCredentials: true });
this.http.post('http://localhost:3000/createNew', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)`
The 'Content-Type': 'multipart/form-data'
header tells the browser that the content of the request should not be encoded. 'Content-Type': 'multipart/form-data'
标头告诉浏览器不应对请求的内容进行编码。 You need this for example when a form requires binary data, like the contents of a file. 例如,当表单需要二进制数据(例如文件的内容)时,您将需要此文件。
Its likely that postman ignores/removes the application/json
one. 邮递员可能会忽略/删除application/json
之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.