首页 > 解决方案 > 如何将图像存储在 S3 存储桶中?

问题描述

在我的快速应用程序中,我将图像保存到我的仓库中的一个文件夹中。

但是我认为这是不正确的,我应该将它们存储在其他地方,我认为 s3 将是一个不错的选择。

我以前从未做过,所以我不知道它是如何工作的。

我当前的代码在缩放后保存图像:

exports.resize = async (req, res, next) => {
  // check if there is no new file to resize
  if (!req.file) {
    next(); // skip to the next middleware
    return;
  }
  const extension = req.file.mimetype.split('/')[1]
  req.body.photo = `${uuid.v4()}.${extension}`
  // now we resize
  const photo = await jimp.read(req.file.buffer)


  await photo.cover(300, 300);
  // await photo.resize(800, jimp.AUTO);

  await photo.write(`./public/uploads/${req.body.photo}`);
  // once we have written the photo to our filesystem, keep going!
  next()
};

将图像保存到 aws s3 的过程是什么?

谢谢

标签: javascriptnode.jsexpressamazon-s3

解决方案


创建文件上传服务

const multer = require('multer');
const multerS3 = require('multer-s3');
const aws = require('aws-sdk');

aws.config.update({
    // Your SECRET ACCESS KEY from AWS should go here,
    // Never share it!
    // Setup Env Variable, e.g: process.env.SECRET_ACCESS_KEY
    secretAccessKey: "ab7786ad6",
    // Not working key, Your ACCESS KEY ID from AWS should go here,
    // Never share it!
    // Setup Env Variable, e.g: process.env.ACCESS_KEY_ID
    accessKeyId: "ab7786ad6",
    region: 'us-east-1' // region of your bucket
});

const s3 = new aws.S3();

创建我们的 Amazon S3 的实例。

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'medium-test',
    acl: 'public-read',
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})

module.exports = upload;

设置上传图片的路径

const express = require("express");
const router = express.Router();
const upload = require('../services/multer');

const singleUpload = upload.single('image')

router.post('/image-upload', function(req, res) {
  singleUpload(req, res, function(err, some) {
    if (err) {
      return res.status(422).send({errors: [{title: 'Image Upload Error', detail: err.message}] });
    }

    return res.json({'imageUrl': req.file.location});
  });
})

module.exports = router;

更多参考:https ://medium.freecodecamp.org/how-to-set-up-simple-image-upload-with-node-and-aws-s3-84e609248792


推荐阅读