我正在尝试使用node.js从网页上传图像到我的S3存储桶。我能够创建一个文件夹,但是无法将图像文件上传到该文件夹中。以下是我在package.json中的依赖项:
"dependencies": {
"aws-sdk": "^2.331.0",
"bcrypt-nodejs": "0.0.3",
"busboy": "^0.2.14",
"busboy-body-parser": "^0.3.2",
"connect-busboy": "0.0.2",
"ejs": "^2.6.1",
"express": "^4.16.3",
"express-handlebars": "^3.0.0",
"express-session": "^1.15.6",
"mysql": "^2.16.0",
"mysql2": "^1.6.1",
"passport": "^0.4.0",
"passport-local-sequelize": "^0.8.0",
"path": "^0.12.7",
"sequelize": "^4.39.0"
}
以下是我正在处理的api_routes.js文件的部分内容:
const bucketName = 'socialmemedia';
const bucketRegion = 'us-east-1';
AWS.config.update({
region: bucketRegion
});
AWS.config.apiVersions = {
s3: '2006-03-01',
};
const s3 = new AWS.S3();
module.exports = function (app) {
// upload image to S3
app.post("/api/upload", function (req, res) {
const file = (req.body.imageUpload);
const busboy = new Busboy({
headers: req.headers
});
busboy.on('finish', function () {
console.log('Upload finished');
console.log(file);
uploadToS3(file);
});
req.pipe(busboy);
});
function uploadToS3(file) {
// console.log(req.body);
const folder = (req.user.username + "/")
console.log("Folder name: " + folder);
const params = {
Bucket: bucketName,
Key: folder,
ACL: 'public-read',
Body: stream
};
s3.upload(params, function (err, data) {
if (err) {
console.log("Error: ", err);
} else {
console.log("Successfully created a folder on S3");
}
});
res.redirect("/feed");
}
};
这里是表单片段:
<form action="/api/upload" method="POST" class="image-form">
<input id="image-upload" class="file-add" type="file" accept="image/*" name="imageUpload"/>
<button type="submit" id="image-upload" class="sinsup-button">Upload Image</button>
</form>
有什么办法可以让图片真正上传到S3存储桶中吗?