javascript - 在 Express FileUpload .mv() 方法中使用函数后不会触发函数的返回语句
问题描述
我正在尝试通过上传文件,Express File Upload
但获取调用它的函数的未定义值。
我有这个功能可以检查用户是选择了单个文件还是多个文件。为了简单起见,我将在单个文件上传中显示问题。那是req.files.fileInput
一个对象而不是对象数组。
这是代码:
const fileCheck = ( file ) => {
if ( Array.isArray( file ) ) {
// ignore this part of the if block as I'm testing it out with single file upload
console.log( 'THE USER WANTS TO UPLOAD MULTIPLE FILES' );
} else if ( typeof file === 'object' ) {
console.log( 'THE USER WANTS TO UPLOAD A SINGLE FILE' );
const uploadPath = `./resources/images/${file.name}`;
file.mv( uploadPath, function ( err ) {
if ( err ) {
console.error( err );
return {
success: false,
message: 'Something went wrong. Please upload again!',
data: null
};
}
return {
success: true,
message: 'File Uploaded Successfully!',
data: file.name
};
});
}
};
const { success, message, data } = fileCheck(req.files.fileInput);
// IT IS UNDEFINED BUT IT IS SUPPOSED TO BE TRUE IF FILE UPLOAD IS SUCCESSFUL.
// IT IS ALSO UNDEFINED INSTEAD OF FALSE IF THERE IS AN ERROR IN FILE UPLOAD.
console.log( success );
我收到此错误:
TypeError: Cannot destructure property 'success' of '(intermediate value)' as it is undefined.
似乎fileCheck
函数的 return 语句在 .mv() 方法中使用后没有被触发。这可能是什么原因?我能做些什么来解决它?
解决方案
您只是从file.mv()
回调函数返回,您也需要返回file.mv()
,以便它渗透到您的fileCheck
函数。
做这个
return file.mv(uploadPath, function (err) {
if (err) {
console.error(err);
return {
success: false,
message: 'Something went wrong. Please upload again!',
data: null,
};
}
return {
success: true,
message: 'File Uploaded Successfully!',
data: file.name,
};
});
编辑
不幸的是file.mv()
,默认情况下似乎没有返回其回调函数的结果。
fileCheck
考虑从这样的地方返回一个承诺
const fileCheck = ( file ) => {
if ( Array.isArray( file ) ) {
console.log( 'THE USER WANTS TO UPLOAD MULTIPLE FILES' );
} else if ( typeof file === 'object' ) {
console.log( 'THE USER WANTS TO UPLOAD A SINGLE FILE' );
const uploadPath = `./resources/images/${file.name}`;
return new Promise((resolve, reject) =>
file.mv( uploadPath, function ( err ) {
if ( err ) {
console.error( err );
return reject({
success: false,
message: 'Something went wrong. Please upload again!',
data: null
});
}
return resolve({
success: true,
message: 'File Uploaded Successfully!',
data: file.name
});
});
}
};
并fileCheck
像这样使用
const { success, message, data } = await fileCheck(req.files.fileInput);
console.log( success );
注意:您必须在其他地方fileCheck
调用父函数async
才能使用await
推荐阅读
- reactjs - 如何有条件地将 props 传递给 React 组件?
- python - Python Compact 函数转换为字符串
- angular - 是否可以以角度形式传递对 ng-template 的有效引用
- python-3.x - 如何从python中的音频中检测语言?
- multithreading - 如何一致且并行地运行 Python 子进程?
- python-3.x - 在 Python 中,如果默认值是方法调用,为什么函数参数值不会在调用时更新?
- java - 我想根据匹配键更新数据库中 2 个表的记录
- jboss - Quarkus:MicroProfile 指标和 Graphite
- django-models - 如何使用django中的模型匹配没有外键关系的两个字段
- javascript - 此地图集层中不允许使用 MongoDB $size,替代方案?