Post Excel file/Blob 休息 API 使用 Angular 4

Post Excel file/Blob to Rest API using Angular 4

我正在使用带文件的输入类型上传 excel 文件,如下所示:

  <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>

读取文件内容:

 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);
    }
}

点击上传后,下面的代码用于上传文件内容。

 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);
                }

            });
    }

但我无法上传文件内容并收到以下响应:

400 错误请求 { "status": "bad_input", "message": "file not found in request payload." }

我可以在 post 请求之前看到文件内容。

终于找到解决办法

模板:

<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>

组件:

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);
        }
    }
}