node.js - 如何检查 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;
解决方案
你需要统计附件的数量——如果字段名为空,你可以假设没有附件):
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;
推荐阅读
- javascript - HTTP 请求,对象/数组解构
- java - 关于 Java 8 OptionalInt.of 参数的问题
- android - 在 Firestore 云数据库的地图视图上绘制多个标记?
- typescript - 在 TSDoc 中如何记录对象?
- mapbox - 如何按状态过滤功能
- python - 如何生成随机用户用户名并插入 django 中的数据库
- java - 如何从字符串资源文件一次设置风味版本代码和版本名称
- sql - 如何从巨大的 csv 文件中清除不良数据
- pandas - 如何在 matplotlib 的 set_xlim 中设置 'y > 0' 公式?
- python - pandas series.gt 如何使用