filefile-uploadangular2-formshtml5-filesystemangular4-httpclient

Post Excel file/Blob to Rest API using Angular 4


I am using input type with file to upload a excel file like below :

  <input type="file" style="display: inline-block;" (change)="readFile($event)" placeholder="Upload file" accept=".xlsx">
  <button type="button" class="btn btn-info" (click)="uploadExcel()" [disabled]="!enableUpload">Upload</button>

For reading file contents :

 public readFile(event) {
    try {
        this.enableUpload = false;
        const reader = new FileReader();
        reader.onload = (e: any) => {
            console.log(e.target.result);
            this.fileContent = e.target.result;
            let binary = "";
            const bytes = new Uint8Array(e.target.result);
            const length = bytes.byteLength;
            for (let i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            const workbook = XLSX.read(binary, { type: 'binary' });
            console.log(workbook);
        };

        reader.readAsArrayBuffer(file);
        console.log(reader);
        this.enableUpload = true;
    } catch (error) {
        console.log('Error reading uploaded file. See below msg for details : \n');
        console.log(error);
    }
}

on click of Upload below code is used to upload the file content.

 public uploadExcel() {
        let formData = new FormData();
        formData.append('file', this.fileContent, 'filename');
        this._commonService
            .commonHttpPostRequest("http://urlforfileupload",
                { file: this.fileContent }, {}
            )
            .subscribe(response => {
                try { 
                    console.log(response);
                } catch (error) {
                    console.log("Error" + error);
                }

            });
    }

But I am unable to upload file contents and getting the below response :

400 Bad Request { "status": "bad_input", "message": "file not found in request payload." }

I can see fileContent before I post the request.


Solution

  • Finally found the solution

    Template :

    <input type="file" [multiple]="multiple" #fileInput class="browse-btn" (change)="readFile()" accept=".xlsx">
    <button type="button" class="btn btn-info btn-lg" (click)="upload()" >Upload</button>
    

    Component :

    public upload() {
        const inputEl: HTMLInputElement = this.inputEl.nativeElement;
        const fileCount: number = inputEl.files.length;
        const formData = new FormData();
        const headers = new Headers();
        headers.set('Accept', 'application/json');
        headers.delete('Content-Type'); // mandate for accepting binary content
        if (fileCount > 0) {
            for (let i = 0; i < fileCount; i++) {
                formData.append('file', inputEl.files.item(i));
            }
            try {
                this.loaderForFileUpload = true;
                this.http
                    .post('http://urlForFileUpload', formData, { headers: headers })
                    .subscribe(response => {
                        if (response.status === 200) {
                            this._toastr.success('File uploaded successfully', 'Success!');
                        }
                    }, error => {
                        this._toastr.error('File contents mismatch', error.statusText);
                    });
            } catch (e) {
                console.log('Error occured while posting uploaded file. See below message for details : \n');
                console.log(e);
            }
        }
    }