在我的快速申请中,我将图像保存到了我的仓库中的一个文件夹中。
但是我不认为这是正确的,我应该将它们存储在其他地方,我认为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的过程是什么?
谢谢
答案 0 :(得分:0)
您可以在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}`);
});
});
};
Ref:AWS Api
答案 1 :(得分:0)
创建文件上传服务
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