NodeJS, Axios - post file from local server to another server

前端 未结 3 595
夕颜
夕颜 2020-12-15 21:23

I have an API endpoint that lets the client post their csv to our server then post it to someone else server. I have done our server part which save uploaded file to our ser

相关标签:
3条回答
  • 2020-12-15 21:50

    I'm thinking the createReadStream is your issue because its async. try this. Since createReadStream extends the event emitter, we can "listen" for when it finishes/ends.

    var newFile = fs.createReadStream(file.path);
    
    // personally I'd function out the inner body here and just call 
    // to the function and pass in the newFile
    newFile.on('end', function() {
      const form_data = new FormData();
      form_data.append("file", newFile);
      const request_config = {
        method: "post",
        url: url,
        headers: {
            "Authorization": "Bearer " + access_token,
            "Content-Type": "multipart/form-data"
        },
        data: form_data
      };
      return axios(request_config);
    });
    
    0 讨论(0)
  • 2020-12-15 21:53

    This is what you really need:

    const form_data = new FormData();
    form_data.append("file", fs.createReadStream(file.path));
    
    const request_config = {
      headers: {
        "Authorization": "Bearer " + access_token,
        "Content-Type": "multipart/form-data"
      },
      data: form_data
    };
    
    return axios
      .post(url, form_data, request_config);
    
    0 讨论(0)
  • 2020-12-15 21:54

    The 2 oldest answers did not work for me. This, however, did the trick:

    const FormData = require('form-data'); // npm install --save form-data
    
    const form = new FormData();
    form.append('file', fs.createReadStream(file.path));
    
    const request_config = {
      headers: {
        'Authorization': `Bearer ${access_token}`,
        ...form.getHeaders()
      }
    };
    
    return axios.post(url, form, request_config);
    

    form.getHeaders() returns an Object with the content-type as well as the boundary.
    For example:

    { "content-type": "multipart/form-data; boundary=-------------------0123456789" }
    
    0 讨论(0)
提交回复
热议问题