如何从Express API POST请求正文中检索excel .xlsx数据?

时间:2020-10-26 14:36:49

标签: node.js angular typescript api express

我有一个Angular前端应用程序,它将excel(.xlsx)文件作为请求主体中的表单数据发送到我的Express端点。

以下是我的Angular服务文件中的功能:

uploadOrder(workOrder: File) {
  const formData: FormData = new FormData();
  formData.append('order', workOrder, workOrder.name);
  return this.http.post(this.uploadOrderUrl, formData);
}

下面是html表单:

<form [formGroup]="orderUploadForm" (ngSubmit)="onSubmit()">
  <input #fileUpload formControlName="orderUpload" type="file" (change)="handleOrderUpload($event.target.files)" accept=".xlsx">
  <button *ngIf="fileToUpload !== null" [disabled]="loading || (fileToUpload === null)">
    <span *ngIf="!loading">
      Upload
    </span>
  </button>
</form>

我的请求有效负载只是参数为order的二进制文件。以下是有效载荷源:

------WebKitFormBoundary6kTGShrkCmA5pcA4
Content-Disposition: form-data; name="order"; filename="sample-order.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


------WebKitFormBoundary6kTGShrkCmA5pcA4--

使用打字稿编写的My Express中间件具有以下配置:

// src/config/app.ts

private config(): void {
  this.app.use(bodyParser.json());
  this.app.use(bodyParser.urlencoded({ extended: true }));
}

端点是这样写的:

app.post('/api/submit-excel', (req: Request, res: Response) => {
  console.log(req.body.order); // <-- req.body.order is returning undefined

  convertExcelToJson(req.body.order); 
  res.status(200).json({ message: "Post request successfull" });
});

我的req.body.order返回了undefined

我的应用程序配置文件中缺少任何内容吗,这就是为什么它无法从请求正文获取数据的原因?非常感谢您提供任何指导或帮助。

编辑:

尝试使用express-fileupload,但看到以下错误:

Error: Cannot find module 'express-fileupload'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\username\Software\Workspace\express-app\dist\config\app.js:5:20)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

我已经安装了依赖项npm i @types/express-fileupload并将其import * as fileUpload from 'express-fileupload';config/app.ts导入到/node_modules/@types/express-fileupload/index中,但仍然没有用。

1 个答案:

答案 0 :(得分:0)

您可以使用express-fileupload

python3 manage.py ...
// src/config/app.ts

private config(): void {
  this.app.use(bodyParser.json());
  this.app.use(bodyParser.urlencoded({ extended: true }));
  // Enable files upload. Don´t forget to import the package
  this.app.use(fileUpload({
    createParentPath: true
  }));
}