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. If the header is 'Content-Type': 'multipart/form-data'
, the client side can send the form data to the server. But in postman application/json will work. I want the same in Angular 4.
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:
<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
. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.