skip to Main Content

I need to upload a file from a Node.js server to another server using axios. I’m using multer to handle the data received from the client. Here’s my code:

const multer = require('multer');
const router = require('express').Router();
const FormData = require('form-data');
const fs = require('fs');

router.post('/profile/:idProfile/post', upload.any(), (req, res) => {
  const file = req.files[0];
  const url = 'https://graph.facebook.com/' + req.params.idProfile + '/photos?access_token=<my-access-token>';
  const fd = new FormData();
  const config = {
    headers: { 'Content-Type': 'multipart/form-data' }
  };

  fd.append('file', fs.createReadStream(file.path), file.path);

  axios.post(url, fd, config)
    .then((res2) => {
      res.send(res2);
    })
    .catch((err) => {
      res.send({
        code: err.response.status,
        error: err.response.data.error
      });
    });
});

I don’t see any problems, but I’m still getting the following error from Facebook’s Graph API:

{
  "code": 400,
  "error": {
    "message": "(#324) Requires upload file",
    "type": "OAuthException",
    "code": 324,
    "fbtrace_id": "HeA2joMhLQ7"
  }
}

I already tried to upload files directly to the Facebook Graph Api url from a simple html page with success. But I’m not able to understand what’s missing here

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution to my problem. I needed to use fd.pipe() and concat to send the image with axios because it's in a binary format:

    fd.pipe(concat({ encoding: 'buffer' }, (data) => {
      axios.post(url, data, { headers: fd.getHeaders() });
    }));
    

    There's more details on this issue here


  2. //Concat the formData.
    const concatenated = await new Promise((resolve, reject) => {
        formData.pipe(concat({ encoding: 'buffer' }, async (data) => {
            resolve(data);
        }))
    })
    
    //Now you can use it.
    const resp = await axios.post(
        `${URL_BASE}/upload_file`,
        concatenated,
        {
            headers: {...formData.getHeaders()}
        }
    );
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search