我正在尝试在我的sails js app上使用AWS SDK。我不断收到此错误:无法确定[object Object]的长度。有谁知道造成这种情况的原因?
以下是代码:
var AWS = require('aws-sdk');
var s3bucket = new AWS.S3({
accessKeyId : 'xxx',
secretAccessKey : 'xxx',
params: {Bucket: 'sweetestspots'}
});
var body = req.file('cover');
s3bucket.upload({Key: 'filename', ACL:'public-read', Body:body}, function(err, data) {
console.log ("data")
console.log (data)
if (err) {
console.log("Error uploading data: ", err);
return res.send("err");
} else {
console.log("Successfully uploaded data to myBucket/myKey");
console.log(data);
return res.send("uploaded");
}
});
答案 0 :(得分:2)
根据aws
Body
的值应为缓冲区,blob或流
upload(params = {}, [options], [callback])
如果有效负载足够大,则使用智能并发处理部件来上传任意大小的缓冲区,blob或流。您可以通过设置选项来配置并发队列大小。
var params = {Bucket: 'bucket', Key: 'key', Body: stream};
s3.upload(params, function(err, data) {
console.log(err, data);
});
您需要像fs.createReadStream(req.file.path)
那样流式传输文件并将其发送到Body
参数
答案 1 :(得分:2)
我也遇到这种错误。问题是您需要将Body
作为Buffer
传递。我是这样做的,问题就没了:
router.post("/upload-image", (req, res) => {
let imageFileName;
const busboy = new BusBoy({ headers: req.headers });
busboy.on("file", (fieldName, file, fileName, encoding, mimetype) => {
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Bad format in the image" });
}
const filePath = path.join(os.tmpdir(), fileName);
const params = {
Bucket: "your bucket name",
Key: fileName,
Body: "",
ACL: "public-read",
ContentType: mimetype,
};
file.on("data", function (data) {
params.ContentLength = data.length;
params.Body = data;
});
// needed to call upload function after a while, because params was not updating immediately
setTimeout(() => {
s3.upload(params, (error, data) => {
if (error) {
return res.status(500).send(error);
}
return res.status(200).json({ imageURL: data.Location });
});
}, 1000);
file.pipe(fs.createWriteStream(filePath));
});
busboy.end(req.rawBody);
});
并且此代码还将解决将图片上传到s3后获得零字节的问题
答案 2 :(得分:2)
我在使用 putObject 上传流时遇到此错误。解决方案是切换到上传或使用缓冲区/blob 而不是流。
答案 3 :(得分:1)
嗨,我遇到了同样的问题, 我发给你的是我的代码。
var s3bucket = new AWS.S3({
accessKeyId: 'xxx',
secretAccessKey: 'xxx+xxx',
});
var body = new Buffer(req.file('cover'), 'base64');
var params = {
Bucket: 'sweetestspots',
Key: 'yourimagename',
Body: body,
ContentEncoding: 'base64',
ContentType: 'image/png',
ACL: 'public-read'
};
s3bucket.upload(params, function(err, data) {
if (err) {
console.log("Error uploading data: ", err);
} else {
console.log("Successfully uploaded data to myBucket" + JSON.stringify(data));
}
});
请尝试此代码。