作者:kkka姐姐_244 | 来源:互联网 | 2023-07-22 16:48
我正在编写此节点脚本,以便将图像上传到s3存储桶。到目前为止,除了存储桶中上传的图像的大小为0 KB以外,到目前为止还不错。这意味着我能够看到它们的名称,但是图像上没有内容。谁能给我一些为什么会发生这种情况?
这是我的代码:
const fs = require('fs');
const AWS = require('aws-sdk');
const cOnfig= require('./config');
//configuring the AWS environment
var s3 = new AWS.S3({
accessKeyId: config.accessKeyId,secretaccessKey: config.secretaccessKey
});
const uploadFile = (fileName) => {
// Setting up S3 upload parameters
const params = {
Bucket: 'mybucket',Key: fileName,// File name you want to save as in S3
Body: fs.readFileSync(fileName)
};
// Uploading files to the bucket
s3.upload(params,function(err,data) {
if (err) {
throw err;
}
console.log(`File uploaded successfully. ${data.Location}`);
});
};
uploadFile("car.png");
uploadFile("aeroplane.png");
uploadFile("sky.png");
我非常感谢您的帮助,因为我确实没有得到可能出问题的地方!
使用createReadStream
作为流读取文件对我来说是正常的。
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create S3 service object
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
// Configure the file stream and obtain the upload parameters
const fs = require('fs');
var fileStream = fs.createReadStream('/file/path');
fileStream.on('error',function(err) {
console.log('File Error',err);
});
var uploadParams = {
Bucket: 'bucket-name',Key: 'key',Body: fileStream
};
s3.upload (uploadParams,function (err,data) {
if (err) {
console.log("Error",err);
} if (data) {
console.log("Upload Success",data.Location);
}
});
参考:
https://docs.aws.amazon.com/sdk-for-Javascript/v2/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-upload-file
,
顺便说一句,您的代码对我来说非常适合多个文件。我已经在同一目录中复制了三个图像文件并运行了代码。所有文件照原样复制到S3。这些都不是零字节。