在Javascript/Angular中以二进制数据的形式(使用readAsArrayBuffer)上传excel文件到



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

我正在使用File reader并将文件读取为二进制文件,如下所示,并传递fileReader。结果给我的Node js控制器调用API。

fileReader.readAsBinaryString (this.file);

在后台,这会抛出一些错误。当我使用fileReader.readAsArrayBuffer(this.file);我不能传递给控制器,因为这是一个对象,而不是一个字符串。

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

使用Angular 2+,你可以使用FormData将文件发送到服务器withHTTPClient (@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);
});
});
}
}

相关内容

  • 没有找到相关文章

最新更新