node.jsexpressrequestjs

writing file from post request in ExpressJS


Working with express to create a file transfer tool, and I've almost gotten everything completed. Just need to figure out how to get the data from the request written to file.

My issue appears to be stemming from not knowing where the file contents are placed in the request object.

My code to process sending the request

let file = watcher.getOneFile(config.thisLocation);
console.dir(file);
let contents = fs.readFileSync(file.fullPath, 'utf-8');
console.log(contents);
let form = {
  attachments: [
    contents
  ]
}
rq.post({
  url: `http://${homeAddress}:${port}/files/?loc=${config.thisLocation}&file=${file.fileName}`,
  headers: {'content-type':'application/x-www-form-urlencoded'},
  formData: form
}, (err, res, body) => {
  // body = JSON.parse(body);
  console.log(body);
});

and when I get the request on the server, I'm not sure where the file contents actually are.

Code for handling the request

app.post('/files', (req, res) => {
  console.log(req.query.loc);
  // console.dir(req);
  let incoming = watcher.getOutputPath(req.query.loc, config.locations);
  console.log(incoming);
  console.dir(req.body);
  // console.log(req.body);
  // let body = JSON.parse(req.body);
  console.log(req.query);
  let filename = path.join(incoming, req.query.file);
  console.log(filename);
  fs.writeFile(filename, req.body, (err) => {
    if(err){
      console.error(err);
    }
    console.log(`Successfully wrote file: ${path.join(incoming, req.query.file)}`);
  });
  res.sendStatus(200);
});

Where on the Request Object is the file contents?


Solution

  • Unfortunately you can't access the file content in any straightforward way. I recommend you to use busboy or similar package to parse form-data requests.

    Here is how can you read file content using busboy and write it to the file system:

    const Busboy = require('busboy');
    
    app.post('/files', (req, res) => {
      const busboy = new Busboy({ headers: req.headers });
    
      busboy.on('file', (fieldname, file, filename, encoding, mime) => {
        const newFilename = `${Date.now()}_${filename}`,
          newFile = fs.createWriteStream(newFilename);
    
        file.pipe(newFile);
    
        file.on('end', () => {
          console.log(`Finished reading ${filename}`);
        });
      });
    
      busboy.on('finish', () => {
        console.log('Finished parsing form');
    
        res.sendStatus(200);
      });
    
      req.pipe(busboy);
    });