我正在使用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;
答案 0 :(得分:1)
您需要计算附件的数量-如果字段名称为空,则可以假定没有附件):
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;