📜  使用多方保存图像和其他字段 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:00.109000             🧑  作者: Mango

代码示例1
◉ server/lib/util/index.js ===>
    const uploadImage =   (file, imgpath, callback)=> {
      if( file.originalFilename=="" ){
          callback(null, { "nofile":true } );
      }else{

          var filePath = file.path;
          var params = {
              Bucket: process.env.AWS_S3_BUCKET,
              Body: fs.createReadStream(filePath),
              Key: imgpath + "/" + Date.now() + "_" + path.basename(filePath),
              ContentType: file.headers['content-type'],
              ACL: 'public-read'
          };

          return new Promise(  (resolve,reject)=>{
              s3.upload(params, function (err, data) {
                  if (err) {
                      reject(err);
                  } else {
                      resolve(data);
                  }
              });
          });
      }
  };
----------------------------------------------------------------------------
◉ server/src/api/routes/auth/authController.js ===>
  
  const multiparty = require('multiparty');
  const { uploadImage } = require('../../../../lib/util');



  async updateProfile(req, res, next) {
          console.log('===='+req.user)
          try {
              let user = await User.findOne({ _id: req.user._id });
              if (user) {
                  let form = new multiparty.Form()
                  form.parse(req, async function(err, fields, files) {
                      let fileupload = files.image[0];
                      console.log('===fields==='+JSON.stringify(fields)+'====')
                      console.log('===files==='+JSON.stringify(files)+'====')


                      _.forOwn( fields,(field,key)=>{
                          user[key] = field[0];
                      })
                      try{
                          console.log(fileupload)

                          let image = await uploadImage( fileupload,'users' );
                          console.log('======fileupload===='+image+"===")
                        // here image and user_name save in schema but user name not display here bqz 
                        // above _.forown(){} method automatic take other field like user_name  
                          user['image'] = image.key;   
                          console.log(user)
                          await user.save();
                          return res.success({language: req.headers['accept-language']},req.__('PROFILE_UPDATED'));
                          }catch(err){
                              return next(err);
                          }
                  }); 
              } else {
                  return res.warn('', req.__('USER_NOT_FOUND'));
              }
          } catch (err) {
              return next(err);
          }
      }