javascript - 如何将图像存储在 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 的过程是什么?
谢谢
解决方案
创建文件上传服务
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
推荐阅读
- pyspark - 使用 Synapse Analytics 将数据帧写入 SQL 专用数据库
- javascript - 如何使用 htlm、js 和 nodejs 在另一个页面中显示画布活动?
- python - 多次从 python 运行程序,但不初始化不同的 shell
- python - 如何从图像中检测线条的高度和重量?
- php - 如何从控制器laravel导出jstree所需的json
- javascript - 同一个 ngFor 中不同类型的组件
- javascript - chrome如何缓存表单输入?
- hsl - 在反应js的数组中声明hsl
- python - 如何连接三个没有行不匹配的熊猫数据框
- spring-data-jpa - AnsiDialect 在 spring-data-jpa 树中不可用