在下面的代码片段中,我使用node-fetch和form-data首先从远程URL检索图像文件,然后将其上传到S3存储桶(在不同的脚本中使用aws-sdk和multer):
问题是,在使用
更新:稍微修改片段以实现Fransebas(第一个答案)的建议并避免异步问题后,我遇到了新问题:保存在本地的图像很好,但上传到S3的副本被部分切断!
附加代码:处理POST上传的路由https://www.schandillia.com/upload/profile-image如下,并且当我使用Postman上传文件时,它运行良好。
import fetch from 'node-fetch';
import fs from 'fs';
import FormData from 'form-data';
const form = new FormData();
const processProfileImg = (imageURL, userID) => {
fetch(imageURL, userID)
.then((response) => {
const dest = fs.createWriteStream(`./temp/${userID}.jpg`);
response.body.pipe(dest);
})
.then((dest) => {
form.append('profileImage', fs.createReadStream(`./temp/${userID}.jpg`));
fetch(`https://www.schandillia.com/upload/profile-image?userID=${userID}`, { method: 'POST', body: form })
.then(response => response.json())
.then(json => console.log(json));
});
};
export default processProfileImg;
问题是,在使用
form-data
函数进行POST之前,需要先将文件在检索时存储到本地。有没有完全绕过这个步骤的方法?我不想将文件保存在本地,我只想从远程URL中获取它并将其POST到上传路由,而不创建本地文件。更新:稍微修改片段以实现Fransebas(第一个答案)的建议并避免异步问题后,我遇到了新问题:保存在本地的图像很好,但上传到S3的副本被部分切断!
附加代码:处理POST上传的路由https://www.schandillia.com/upload/profile-image如下,并且当我使用Postman上传文件时,它运行良好。
import dotenv from 'dotenv';
import express from 'express';
import aws from 'aws-sdk';
import multerS3 from 'multer-s3';
import multer from 'multer';
import path from 'path';
dotenv.config();
const router = express.Router();
// Set up S3
const s3 = new aws.S3({
accessKeyId: process.env.IAM_ACCESS_KEY_ID,
secretAccessKey: process.env.IAM_SECRET_ACCESS_KEY,
});
const checkFileType = (file, cb) => {
// Allowed ext
const filetypes = /jpeg|jpg/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
}
return cb('Error: JPEG Only!');
};
// Single Upload
const profileImgUpload = multer({
storage: multerS3({
s3,
contentType: multerS3.AUTO_CONTENT_TYPE,
bucket: `${process.env.S3_BUCKET_NAME}/w`,
acl: 'public-read',
key(req, file, cb) {
cb(null, req.query.userID + path.extname(file.originalname));
},
}),
limits: { fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
fileFilter(req, file, cb) {
checkFileType(file, cb);
},
}).single('profileImage');
router.post('/profile-image', (req, res) => {
profileImgUpload(req, res, (error) => {
if (error) {
console.log('errors', error);
res.json({ error });
} else if (req.file === undefined) {
// If File not found
console.log('Error: No File Selected!');
res.json('Error: No File Selected');
} else {
// If Success
const imageName = req.file.key;
const imageLocation = req.file.location;
// Save the file name into database into profile model
res.json({
image: imageName,
location: imageLocation,
});
}
});
});
// End of single profile upload
// We export the router so that the server.js file can pick it up
module.exports = router;