gpt4 book ai didi

javascript - 使用 Node.js 将图像上传到 AWS S3 存储桶。 JS

转载 作者:搜寻专家 更新时间:2023-11-01 00:19:44 25 4
gpt4 key购买 nike

我正在尝试使用 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 存储桶的任何想法?

最佳答案

我弄明白了,谢谢你的帮助@me。我使用的是 s3.upload 而不是 s3.putObject。回答以帮助将来可能遇到此问题的任何其他人。

  // upload image to S3
app.post("/api/upload", function (req, res) {
const folder = (req.user.username + "/");
const file = (req.body.imageUpload);
const params = {
Bucket: bucketName,
Key: (folder + file),
ACL: 'public-read',
Body: file
};
console.log("Folder name: " + folder);
console.log("File: " + file);


s3.putObject(params, function (err, data) {
if (err) {
console.log("Error: ", err);
} else {
console.log(data);
}
});
res.redirect("/feed");
});

关于javascript - 使用 Node.js 将图像上传到 AWS S3 存储桶。 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52794902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com