I have a file upload in the form. I need to create post request to backend with this uploaded file and some other form fields too.
Below is my code:
fileChange(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
this.file = fileList[0];
this.form.get('file_upload').setValue(this.file);
}
}
onClick(){
const val = this.form.value;
const testData = {
'file_upload': this.file,
'id': val.id,
'name' : val.name,
'code': val.code,
};
this.http.post('https://url', testData,
.subscribe(
response => {
console.log(response);
});
}
Every field value is being sent to backend except the uploaded file. ow do I send uploaded file along with form fields to backend? Let me know if any additional information is needed.
You are trying just simple pass file data
'file_upload': this.file,
this is wrong
There is quite a lot of ways how to upload file, I like to use FormData, example in you case:
let testData:FormData = new FormData();
testData.append('file_upload', this.file, this.file.name);
this.http.post('https://url', testData).subscribe(response => {
console.log(response);
});
More details here File Upload In Angular?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With