首页 > 解决方案 > 在Javascript / Angular中以二进制数据的形式(使用readAsArrayBuffer)将excel文件上传到后端

问题描述

我必须从 UI 上传和读取一个 excel 文件,并将文件数据以二进制形式发送到后端 API。

我正在使用文件阅读器并将文件作为二进制文件读取,如下所示,并将 fileReader.result 传递给我的 Node js 控制器以调用 API。

fileReader.readAsBinaryString(this.file);

在后端,这会引发一些错误。当我使用 fileReader.readAsArrayBuffer(this.file) 时;我无法传递给控制器​​,因为这是对象,而不是字符串。

我该如何解决这个问题,我想将从 readAsArrayBuffer 获得的数据传递给 API。

标签: javascriptangulartypescriptbinaryfilereader

解决方案


使用 Angular 2+,您可以将文件发送到服务器的一种方法是使用带有HTTPClient (@angular/common/http)的FormData。我假设您正在使用 TypeScript,并且当您单击上传时,您正在调用一个名为upload的函数。因此,这是一个简单的示例,您可以将其作为参考并根据您的情况进行调整。该文件将以二进制形式发送:

import { HttpClient } from '@angular/common/http';

export class MyFormService {

 constructor(private _http: HttpClient) {}

 upload(data: IDataModel): Promise<IMyServerResponse> {
    return new Promise(async (resolve, reject) => {
      const url = 'https://example.com/api/';

      const formData = new FormData();
     
     //If you have just an attachment consider this ---------------------------
     //As suggestion, encode or replace special characters from fileName.
     //The function this.parseFileName is basically doing it.
     const name = this.parseFileName(data.attachment.name);
     formData.append('attachment', data.attachment.file, name);
     //-----------------------------------------------------------------------


      //Or if you have multiple files, consider this one ---------------------
      //Pay attention to the [] after attachment;
      for (const item of data.attachmentList) {
        
        const name = this.parseFileName(item.name);
        formData.append('attachment[]', item.file, name);
      }
     //-----------------------------------------------------------------------

      //Here you post your form data with progress reporting -----------------
      await this._http.post(url, formData, { reportProgress: true, observe: 'events', responseType: 'json' })
        .subscribe(async event => {
            if (event.type === HttpEventType.UploadProgress) {
               //Here you can check the progress based on event.loaded 
               //divided by event.total and show to your user.
               
               //Code omitted 
               ...
               ...
            }

            if (event.type === HttpEventType.Sent) {
              //Here your data has been sent to the server.
              //So, based on your server, you can manipulate the request based on 
              //the form field.
            }

            if (event.type === HttpEventType.Response) {
              const serverResponse = event.body as IMyServerResponse;

              //Code omitted
              ...
              ...
              ...

              resolve(serverResponse);
            }
          },
          error => {
            let errorMessage;

            //Code omitted
            ...
            ...
            ...

            reject(error);
          });
    });
  }
}

推荐阅读