angular 4- How do I send file in POST to backend
Asked Answered
H

2

8

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.

Herminiahermione answered 24/7, 2018 at 21:35 Comment(0)
D
15

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?

Disclose answered 24/7, 2018 at 21:46 Comment(2)
I tried using formData too. But the formData became empty when I'm making the post request.Herminiahermione
@Herminiahermione did you tried adding headers? headers.append('Content-Type', 'multipart/form-data');Disclose
B
0

Assuming you're handling the file upload properly on the server (usually some type of npm package like multer or busboy),

you need to use an npm package on the angular side to handle the the multipart form data.

ng-2-file-upload is one of many that work.

https://www.npmjs.com/package/ng2-file-upload

Bendicta answered 24/7, 2018 at 21:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.