Uploading image to amazon s3 using multer-s3 nodejs

前端 未结 6 1928
遥遥无期
遥遥无期 2020-12-04 15:45

I am trying to upload an image to amazon s3 using multer-s3, but I am getting this error:

TypeError: Expected opts.s3 to be object node

6条回答
  •  情书的邮戳
    2020-12-04 16:38

    /*** Using Multer To Upload Image image is uploading */

    const fileStorage = multer.diskStorage({
      destination: function(req, file, cb) {
        cb(null, "./public/uploads");
      },
      filename: function(req, file, cb) {
        cb(null, file.originalname);
      }
    });
    
    /** AWS catalog */
    
    aws.config.update({
      secretAccessKey: process.env.SECRET_KEY,
      accessKeyId: process.env.ACCESS_KEY,
      region: "us-east-1"
    });
    
    const s3 = new aws.S3();
    const awsStorage = multerS3({
      s3: s3,
      bucket: process.env.BUCKET_NAME,
      key: function(req, file, cb) {
        console.log(file);
        cb(null, file.originalname);
      }
    });
    
    const upload = multer({
      storage: awsStorage(),
      /** in above line if you are using local storage in ./public/uploads folder than use
       ******* storage: fileStorage,
       * if you are using aws s3 bucket storage than use
       ******* storage: awsStorage(),
       */
      limits: { fileSize: 5000000 },
      fileFilter: function(req, file, cb) {
        checkFileType(file, cb);
      }
    });
    app.post("/user-profile-image", upload.single("profile"), (req, res, err) => {
      try {
        res.send(req.file);
      } catch (err) {
        res.send(400);
      }
    });
    
    const checkFileType = (file, cb) => {
      const filetypes = /jpeg|jpg|png|gif/;
      const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
      const mimetype = filetypes.test(file.mimetype);
    
      if (mimetype && extname) {
        return cb(null, true);
      } else {
        cb("Error: Images Only!");
      }
    };
    

提交回复
热议问题