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

余生长醉 提交于 2021-01-29 12:33:41

问题


I am trying transfer a file from a nestJS API to Python Flask API.

This process will be triggered by a POST request (FormData: file) on nest API. Then the nest api should send the file to Python api.

The HttpService from nestJS use Axios. So my goal is basically to send file with axios from NodeJS.

FormData is not available on node JS so I installed Nmp FormData .

Python

Python Code, which I think is working properly because Postman request pass without any problems.

@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.

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

  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.

How to correctly transfer request's file to another api with axios ?

Issue about this topic: Axios issue Also tried this Axios fix


回答1:


@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 });
}


来源:https://stackoverflow.com/questions/58682023/transfer-requests-file-from-api-to-api-nestjshttpservice-axios-to-pythonfl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!