我想使用javascript删除amazon s3中的文件。我已经使用javascript将文件上传到s3了。任何想法请帮助
答案 0 :(得分:24)
您可以使用s3中的js方法: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObject-property
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./credentials-ehl.json');
var s3 = new AWS.S3();
var params = { Bucket: 'your bucket', Key: 'your object' };
s3.deleteObject(params, function(err, data) {
if (err) console.log(err, err.stack); // error
else console.log(); // deleted
});
请注意,S3永远不会返回该对象已被删除。 你必须在getobject,headobject,waitfor等之前或之后检查它
答案 1 :(得分:14)
你可以使用这样的结构:
var params = {
Bucket: 'yourBucketName',
Key: 'fileName'
/* where value for 'Key' equals 'pathName1/pathName2/.../pathNameN/fileName.ext' - full path name to your file without '/' at the beginning */
};
s3.deleteObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
别忘了把它包装到承诺。
答案 2 :(得分:3)
在删除文件之前,您必须检查1)文件是否在存储桶中,因为如果文件在存储桶中不可用并使用deleteObject
API,则不会引发任何错误2){{ 1}}。通过使用CORS Configuration
API,可以在存储桶中提供文件状态。
headObject
由于参数是恒定的,因此最好与AWS.config.update({
accessKeyId: "*****",
secretAccessKey: "****",
region: region,
version: "****"
});
const s3 = new AWS.S3();
const params = {
Bucket: s3BucketName,
Key: "filename" //if any sub folder-> path/of/the/folder.ext
}
try {
await s3.headObject(params).promise()
console.log("File Found in S3")
try {
await s3.deleteObject(params).promise()
console.log("file deleted Successfully")
}
catch (err) {
console.log("ERROR in file Deleting : " + JSON.stringify(err))
}
} catch (err) {
console.log("File not Found ERROR : " + err.code)
}
一起使用。如果在s3中找不到该文件,则会引发错误const
。
如果要在存储桶中应用任何操作,则必须在AWS的相应存储桶中更改NotFound : null
的权限。用于更改权限CORS Configuration
并添加此代码。
Bucket->permission->CORS Configuration
有关CROS配置的更多信息:https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html
答案 3 :(得分:1)
您可以使用deleteObjects
API一次删除多个对象,而不必为要删除的每个键调用API。帮助节省时间和网络带宽。
您可以执行以下操作-
var deleteParam = {
Bucket: 'bucket-name',
Delete: {
Objects: [
{Key: 'a.txt'},
{Key: 'b.txt'},
{Key: 'c.txt'}
]
}
};
s3.deleteObjects(deleteParam, function(err, data) {
if (err) console.log(err, err.stack);
else console.log('delete', data);
});
有关参考,请参见-https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property
答案 4 :(得分:-1)
您可以点击此GitHub gist链接https://gist.github.com/jeonghwan-kim/9597478。
delete-aws-s3.js:
var aws = require('aws-sdk');
var BUCKET = 'node-sdk-sample-7271';
aws.config.loadFromPath(require('path').join(__dirname, './aws-config.json'));
var s3 = new aws.S3();
var params = {
Bucket: 'node-sdk-sample-7271',
Delete: { // required
Objects: [ // required
{
Key: 'foo.jpg' // required
},
{
Key: 'sample-image--10.jpg'
}
],
},
};
s3.deleteObjects(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});