Kiren S
Kiren S

Reputation: 3097

How to check atleast one file is present in the request in Express Framework

I am using Busboy for extracting files from request. Below is my code. I want to throw an exception if there is 0 files attached to the request.

const busboy = new Busboy({headers: req.headers});
busboy.on('file', (fieldname: string, file: any, filename: string, encoding: string, mimetype: string) => {
   const uuid = uuidv4();
   const newFileName = uuid + '-' + filename;
   this.createDestination();
   const destination = this.getDestination();
   const savePath = path.join(destination, newFileName);
   this.setFilePaths(savePath, uuid);
   file.pipe(fs.createWriteStream(savePath));
});

busboy.on('finish', () => {
   const filesToBeUploaded = this.getFilePaths();
      this.fileUploaderService.upload(filesToBeUploaded);
   });

busboy.on('error', function (err: any) {
   console.error('Error while parsing the form: ', err);
});

req.pipe(busboy);
return true;

Upvotes: 0

Views: 45

Answers (1)

stdob--
stdob--

Reputation: 29172

You need to count the number of attachments - if the fieldname is empty, you can assume that there is no attachment):

const busboy = new Busboy({headers: req.headers});
var fileCounter = 0; // File counter 
busboy.on('file', (fieldname: string, file: any, filename: string, encoding: string, mimetype: string) => {
   if (filename.length === 0) {
     // https://github.com/mscdex/busboy/blob/master/README.md#busboy-special-events
     file.resume();
   } else {
     const uuid = uuidv4();
     const newFileName = uuid + '-' + filename;
     this.createDestination();
     const destination = this.getDestination();
     const savePath = path.join(destination, newFileName);
     this.setFilePaths(savePath, uuid);
     file.pipe(fs.createWriteStream(savePath));

     fileCount++; // Increase the counter
   }
});

busboy.on('finish', () => {
   // Check the counter and emit an error message if necessary
   if (fileCount === 0) {
     this.emit('error', new Error('No attached files...'));
   } else {
     const filesToBeUploaded = this.getFilePaths();
     this.fileUploaderService.upload(filesToBeUploaded);
   }
});

busboy.on('error', function (err: any) {
   console.error('Error while parsing the form: ', err);
});

req.pipe(busboy);
return true;

Upvotes: 1

Related Questions