【问题标题】:Upload an excel file to backend in the form of binary data(using readAsArrayBuffer) in Javascript/Angular在Javascript / Angular中以二进制数据的形式(使用readAsArrayBuffer)将excel文件上传到后端
【发布时间】:2021-10-02 09:40:42
【问题描述】:

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

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

fileReader.readAsBinaryString(this.file);

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

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

【问题讨论】:

  • 您不需要以 binaryString 格式读取文件,只需按原样上传/发送文件
  • 好的,但我无法在 API 中发送 this.file,我必须将其作为字符串或缓冲区发送;该怎么做?
  • 我需要更多代码来帮助你,但基本上它最终会是:fetch(url, { body: new File(...) })

标签: javascript angular typescript binary filereader


【解决方案1】:

使用 Angular 2+,将文件发送到服务器的一种方法是使用 FormDataHTTPClient (@angular/common/http)。我假设您正在使用 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);
          });
    });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2016-02-18
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多