0

I followed this tutorial to perform file upload and was trying to send the form data with it as well Below is the code for the filechange event

    onFileChange(event) {
        let fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            console.log("gettign file ...")
            let file: File = fileList[0];
            this.formData.append('photoupload', file, file.name);
        }
    }

When clicked on submit button below code gets executed

    let body = JSON.stringify(this.personal);
    this.formData.append("personal", body);
    const headers = new HttpHeaders({
        'Authorization' : 'my-auth-token'
    });

    this.http.post('/api/fmng/create', this.formData, {
        headers: headers
    }).subscribe(data => {
        console.log(data);
    });

On the server side I am only able to get the file using req.file() but when I do req.allParams() there is no data in it. Also trying to console.log the formdata is giving empty result in the angular app.

Edit -->

If I make another post request with just the body then I get the data. So, this might not be a proper way to append the form data.

    this.http.post('/api/fmng/create', body, {
        headers: headers
    }).subscribe(data => {
        console.log(data);
    });
Tech Team
  • 109
  • 13

2 Answers2

0
onFileChange(event) {
        let fileList: FileList = event.target.files;
        if (fileList.length > 0) {
            console.log("gettign file ...")
            let file: File = fileList[0];
            const fileBlob= new Blob([file], { type: "<content-type>" });
            this.formData.append('photoupload', fileBlob);
        }
    }

You need to send a blob here.

0

I had to append the text parameters before appending the file to the formdata

    let body = JSON.stringify(this.personal);
    this.formData.append("personal", body);
    this.formData.append('photoupload', this.file, this.file.name);
    const headers = new HttpHeaders({
        'Authorization' : 'my-auth-token'
    });

    this.http.post('/api/fmng/create', this.formData, {
        headers: headers
    }).subscribe(data => {
        console.log(data);
    });

This solved the issue.

Tech Team
  • 109
  • 13