简体   繁体   English

将请求的文件从 API 传输到 API: NestJS(HttpService: Axios) 到 Python(flask)

[英]Transfer request's file from API to API: NestJS(HttpService: Axios) to Python(flask)

I am trying transfer a file from a nestJS API to Python Flask API.我正在尝试将文件从nestJS API 传输到 Python Flask ZDB974238714CA8DE634A7ACED0

This process will be triggered by a POST request (FormData: file) on nest API.此过程将由嵌套 API 上的 POST 请求(FormData:文件)触发。 Then the nest api should send the file to Python api.然后嵌套 api 应该将文件发送到 Python api。

The HttpService from nestJS use Axios. NestJS 的 HttpService 使用 Axios。 So my goal is basically to send file with axios from NodeJS.所以我的目标基本上是从 NodeJS 发送带有 axios 的文件。

FormData is not available on node JS so I installed Nmp FormData . FormData 在节点 JS 上不可用,所以我安装了Nmp FormData

Python Python

Python Code, which I think is working properly because Postman request pass without any problems. Python 代码,我认为它工作正常,因为 Postman 请求通过没有任何问题。

@app.route('/route', methods=['POST'])
def user():

    params_data = json.load(request.files.get('file'))

    return 'OK'

NestJS巢穴

On the nest side, I tried a lot a things.在鸟巢方面,我尝试了很多东西。

But the main idea is the following: Use formData.getHeaders as axios headers and put data inside the axios config.但主要思想如下:使用 formData.getHeaders 作为 axios 标头并将数据放入 axios 配置中。

app.controller.ts app.controller.ts

    @Post()
    uploadFile(@Req() request: Request) {
        // request is Express request
        const formData: any = new FormData();
        let newFile;
        if (request.hasOwnProperty('file')) {
            newFile = (request as any).file; // This is working 
        }
        formData.append('file', newFile.buffer, 'filename');

        return this.appService.launchOptim(formData);
    }

app.service.ts应用服务.ts

  public launchOptim(modelData: FormData) {

    const axiosConfig: AxiosRequestConfig = {
      headers: modelData.getHeaders(),
      data: modelData,
    };


    return this.http.post('http://localhost:5000/route', modelData, axiosConfig)
               .pipe(map(result => result.data));

  }

And then, with that configuration, request.files in python code stays always empty.然后,使用该配置,python 代码中的request.files始终为空。

How to correctly transfer request's file to another api with axios?如何使用 axios 将请求的文件正确传输到另一个 api?

Issue about this topic: Axios issue Also tried this Axios fix关于此主题的问题: Axios 问题还尝试了此Axios 修复

@Post()
@UseInterceptors(FileInterceptor('file'))
uploadFile(@Req() request: Request, @UploadedFile() file,) {
    var FormData = require("form-data");
    const formData = new FormData();
    formData.append('file', file.buffer, { filename: file.originalname });
    const headers = {
        ...formData.getHeaders(),
        "Content-Length": formData.getLengthSync()
    };
    await axios.post(requestAPI, formData, { headers });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM