【问题标题】:How to store Images in S3 bucket?如何将图像存储在 S3 存储桶中?
【发布时间】:2019-05-16 10:10:55
【问题描述】:

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

但是我认为这是不正确的,我应该将它们存储在其他地方,我认为 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 的过程是什么?

谢谢

【问题讨论】:

    标签: javascript node.js express amazon-s3


    【解决方案1】:

    创建文件上传服务

    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

    【讨论】:

      【解决方案2】:

      您可以在 npm 上使用 AWS SDK

      您需要从这里配置包以连接到您的存储桶..

      一些用法是:

      const AWS = require('aws-sdk');
      const fs = require('fs');
      
      const s3 = new AWS.S3({
          accessKeyId: process.env.AWS_ACCESS_KEY,
          secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
      });
      

      \ 您可以在 nodeJS 中将图像转换为 base64 以便稍后发送。

      并写了一个常规的上传方法:

      const uploadFile = () => {
        fs.readFile(fileName, (err, data) => {
           if (err) throw err;
           const params = {
               Bucket: 'testBucket', //  bucket name
               Key: 'image.png', // filename
               Body: JSON.stringify(data, null, 2)
           };
           s3.upload(params, function(s3Err, data) {
               if (s3Err) throw s3Err;
               console.log(`File uploaded successfully at ${data.Location}`);
           });
        });
      };
      

      参考:AWS Api

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2018-03-20
      • 2019-10-18
      • 2020-08-15
      • 1970-01-01
      • 2021-08-09
      • 2019-08-17
      相关资源
      最近更新 更多