首页 > 解决方案 > 在 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() 方法中使用后没有被触发。这可能是什么原因?我能做些什么来解决它?

标签: javascriptnode.jsexpressmongoosefile-upload

解决方案


您只是从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


推荐阅读