使用Node.js在S3中上传图片

时间:2018-11-14 11:18:54

标签: node.js amazon-s3

我正在尝试使用节点js将图像上传到s3。我正在使用multer-s3。 当我尝试从s3打开图像时,它显示“预览不可用。您的文件可能已损坏”。我也尝试了fs,但结果仍然相同。

services/file-upload.js

     const s3Config = new aws.S3({
        secretAccessKey: config.awsCredentials.secretAccessKey,
        accessKeyId: config.awsCredentials.accessKeyId,
        region: config.awsCredentials.region,
        bucket: 'bucketname',
    });

    const fileFilter = (req, file, cb) => {
      if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
          cb(null, true)
      } else {
          cb(null, false)
      }
    }

    const multerS3Config = multerS3({
      s3: s3Config,
      bucket: 'bucketname',
      metadata: function (req, file, cb) {
          cb(null, { fieldName: file.fieldname });
      },
      key: function (req, file, cb) {
          console.log(file)
          cb(null, new Date().toISOString() + '-' + file.originalname)
      }
    });

    const upload = multer({
      storage: multerS3Config,
      fileFilter: fileFilter,
      limits: {
          fileSize: 1024 * 1024 * 5 // we are allowing only 5 MB files
      }
    })
controller.js
const upload = require('../services/file-upload');
var Uploader = require('s3-image-uploader');
const singleUpload = upload.single('file');
singleUpload(req, res, function(err) {
                 if (err) {
                   return res.status(422).send({errors: [{title: 'Image Upload Error', detail: err.message}] });
                 }

                return res.json({'imageUrl': "uploaded successfully"});
              });

0 个答案:

没有答案