I am trying to upload an image in angular 2 , i have no error listed but there is no change in the position the file added detailed code is given below
**.ts**
............
onFileChange(event) {
if(event.target.files.length > 0) {
let file = event.target.files[0];
this.fileName = file.name;
this.imageUpload['upload'] = this.fileName;
this.form.get('upload').setValue(file);
console.log(file);
console.log('filename',this.fileName);
}
}
private prepareSave(): any {
let inputVal = new FormData();
inputVal.append('upload', this.form.get('upload').value,this.imageUpload['upload']);
console.log(inputVal);
return inputVal;
}
onSubmit() {
this.imageUpload['upload'] = this.fileName;
const formModel = this.prepareSave();
this.loading = true;
var body = formModel;
let url = this.ImageUploadURL;
let headers = new Headers({ 'Content-Type': 'multipart/form-data' ,'Authorization': 'Bearer ' + this.accountsService.accessToken });
let options = new RequestOptions({ headers: headers });
console.log(options);
console.log(body);
console.log(url);
// In a real-world app you'd have a http request / service call here like
return this.http.post(url, body, options)
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
...............
in console its getting success
the method is post with url and { upload:"" }
what might be the error that there is no change on desired portion?
is there any other way ?
In Angular, when using multipart form-data and you are using FormData object, you MUST NOT specifiy the Content-Type header.
By doing so you are preventing the http stack to set it to the proper value which MUST include the boundary value.
Just remove the content type header and let the formatter handle that for you, and you should be fine.