2

我正在使用multeraws-sdkmulter-s3 包以及 express。

当用户编辑个人资料时,用户可能会更改个人资料图片/头像。

我已经通过了 multer 对象

multer({storage: multer.memoryStorage()}).single('profileHeroImageEdit')

如果文件具有当前请求,那么我会将文件上传到 s3 存储桶,但我没有从upload_replace收到任何响应,其中req.file.location将提供 S3 存储桶的 url(文件的位置)。在upload_replace 中 ,我可以获取要上传的文件(req.file),但我想要上传文件到 S3 bucket 的位置。

我错过了什么?帮助将不胜感激

router.put("/:id",multer({ storage: 
multer.memoryStorage()}).single('profileHeroImageEdit'), 
middleware.checkProfileOwnership,function(req, res){
    if(isFileExists(req)==false){
        delete req.body.profileHeroImage      

     }
     else{
         console.log('file has')
         var upload_replace = multer({
            limits:{
                fileSize:MAX_FILE_SIZE,
                files:1
            },
            storage: multerS3({
                s3: photoBucket,
                bucket: BucketName,
                acl: 'public-read',
                metadata: function (req, file, cb) {
                    cb(null, { fieldName: file.fieldname });
                },
                key: function (req, file, cb) {
                    cb(null,Date.now().toString())

                }
            })
        }).single('profileHeroImageEdit') 

        upload_replace(req, res, function (err,log) {
           console.log('request log')
            console.log(req.file.location)
           console.log()
        }); 


     }
    Profile.findByIdAndUpdate(req.params.id, req.body.profile, function(err, updatedProfile){
        if (err){
            res.redirect("/profiles");
        } else {
            res.redirect("/profiles/" + req.params.id);
        }
    });
});

function isFileExists(request){
    if(request.file)
    {
        return true 
    }
    else{
        return false
    }
}
4

2 回答 2

1

我有使用 multer 和 aws-sdk 的完整代码

  1. 包括这个文件和 npm install all

    //aws s3 packages
    const aws = require("aws-sdk");
    const multerS3 = require("multer-s3");
    const multer = require("multer");
    const path = require("path");
    
  2. 然后

    //profile image upload start
    const s3 = new aws.S3({
      accessKeyId: "***",
      secretAccessKey: "***",
      Bucket: "***"
    });
    
    //Singe profile image upload
    
    const profileImgUpload = multer({
      storage: multerS3({
        s3: s3,
        bucket: "***",
        acl: "public-read",
        key: function(req, file, cb) {
          cb(
            null,
            path.basename(file.originalname, path.extname(file.originalname)) +
              "-" +
              Date.now() +
              path.extname(file.originalname)
          );
        }
      }),
      limits: { fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
      fileFilter: function(req, file, cb) {
        checkFileType(file, cb);
      }
    }).single("profileImage");
    
    // getExtension of file by this function
    function getExtension(filename) {
      var parts = filename.split(".");
      return parts[parts.length - 1];
    }
    
    //checkfile type of input function
    function checkFileType(file, cb) {
      const ext = getExtension(file.originalname);
      switch (ext.toLowerCase()) {
        case "jpeg":
        case "jpg":
        case "png":
        case "gif":
          return cb(null, true);
      }
      cb("Error: Images Only!");
    }
    
    router.post(
      "/image",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        profileImgUpload(req, res, error => {
          if (error) {
            res.json({ error: error });
          } else {
            //here we can get req.body
            const userDp = {};
    
            //end of getting values
    
            // If File not found then dont store anything
            if (req.file !== undefined) userDp.dpUrl = req.file.location;
            // Save the file name into database into profile model
    
            User.findOne({ email: req.user.email }).then(user => {
              if (user) {
                // Update
                User.findOneAndUpdate(
                  { email: req.user.email },
                  { $set: userDp },
                  { new: true }
                ).then(user => res.json(user));
              } else {
                res.json({ msg: "not able not update data" });
              }
            });
          }
        });
      }
    );
    

3.需要通过使用从反应前端发送数据

const data = new Formdata();
data.append()

并且还包括标题

于 2019-01-05T13:58:52.687 回答
0

添加一个监听器,用于将照片上传到 S3 的 OutgoingMessage 完成。图书馆on-finished对此很方便。

const onFinished = require('on-finished');
const print = process._rawDebug;

uploadReplace(req, null, function (err) {
  onFinished(req, function () {
    if (err) print(err);
    print(req.file.location);
    // Other things can be done here
  })
});
于 2018-04-06T22:06:38.557 回答