Home > Blockchain >  Send multiple files from one API to another with NodeJS , multer and Axios
Send multiple files from one API to another with NodeJS , multer and Axios

Time:12-29

I have an API in one nodejs project as below which receive multiple attachment from UI:

const upload = multer()
router.post('/upload', upload.array("attachments"),controller.getSomething);

getSomething is supposed to call another POST API using Axios only, which is in another NodeJs project which accept these attachments and process it. It as well accept multiple files via multer.

I am unsure how could i send multiple files as a request from one Nodejs project to another at once. could you please favour.

CodePudding user response:

I had to set formdata as below:

const formData=new FormData();
 for(let file of req.files){
    formData.append("attachments",file.buffer,file.originalname);
 }

And passed the formdata to other api via axios.

CodePudding user response:

You can do the following steps:

  1. When you upload the temporary files (coming from UI), save them in the temporary folder.

  2. Pass all the files names to the POST API using Axios.

  3. In the post API, read all the files from the temporary folder and stream them to the destination.

controller.getSomething = (req, res, next) => {
       // get the file names
      const fileNames = req.files.map(filename => filename);
        
      // now post this filenames to the 
      axios.post('/pathname', {fileNames}) 
      // or, you can use get request
}

Reading files in the post Request:

var promises= ['file1.css', 'file2.css'].map(function(_path){
    return new Promise(function(_path, resolve, reject){
        fs.readFile(_path, 'utf8', function(err, data){
            if(err){
               console.log(err);
               resolve("");    //following the same code flow
            }else{
               resolve(data);
            }
        });
    }.bind(this, _path));
});

Promise.all(promises).then(function(results){
    //Put your callback logic here
    response.writeHead(200, {"Content-Type": "text/css"});
    results.forEach(function(content){response.write(content)});
    response.end();
});

#copied from this link. You should check the different answers that can help you.

  • Related