简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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