首页 > 解决方案 > 如何检查 Express Framework 中的请求中是否存在至少一个文件

问题描述

我正在使用 Busboy 从请求中提取文件。下面是我的代码。如果请求附加了 0 个文件,我想抛出异常。

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;

标签: node.jsexpress

解决方案


你需要统计附件的数量——如果字段名为空,你可以假设没有附件):

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;

推荐阅读