Aws s3使用javascript删除对象

use*_*960 25 javascript amazon amazon-s3 amazon-web-services aws-sdk

我想使用javascript删除amazon s3中的文件.我已经使用javascript将文件上传到s3了.任何想法请帮助

小智 38

您可以使用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
});
Run Code Online (Sandbox Code Playgroud)

请注意,S3永远不会返回该对象已被删除.你必须在getobject,headobject,waitfor等之前或之后检查它

  • 如果使用异步/等待,则必须最后添加`.promise()`。例如:`await s3.deleteObject(params).promise()` (2认同)

ban*_*der 19

在删除文件之前,您必须检查 1) 文件是否在存储桶中,因为如果文件在存储桶中不可用并且使用deleteObjectAPI,这不会引发CORS Configuration存储桶的任何错误 2) 。通过使用headObjectAPI 给出存储桶中的文件状态。

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)
}
Run Code Online (Sandbox Code Playgroud)

由于 params 是常量,因此最好将它与const. 如果在 s3 中找不到该文件,则会引发错误NotFound : null

如果要在存储桶中应用任何操作,则必须更改CORS ConfigurationAWS 中相应存储桶中的权限。用于更改权限Bucket->permission->CORS Configuration并添加此代码。

<CORSConfiguration>
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Run Code Online (Sandbox Code Playgroud)

有关 CROS 配置的更多信息:https ://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html


Vit*_*hyn 16

你可以使用这样的结构:

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
});
Run Code Online (Sandbox Code Playgroud)

别忘了将它包装到Promise中.

  • 即使对象不存在,响应也是相同的 (2认同)

小智 10

您可以关注此 GitHub gist 链接https://gist.github.com/jeonghwan-kim/9597478

删除-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
});
Run Code Online (Sandbox Code Playgroud)


Ani*_*kur 6

您可以使用deleteObjectsAPI一次删除多个对象,而不必为要删除的每个键调用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);
});
Run Code Online (Sandbox Code Playgroud)

有关参考,请参阅-https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObjects-property


MD *_*YON 5

非常直接

首先,创建 s3 的实例并使用凭据配置它

const S3 = require('aws-sdk').S3;

const s3 = new S3({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION
});
Run Code Online (Sandbox Code Playgroud)

然后,按照文档进行操作


 var params = {
  Bucket: "ExampleBucket", 
  Key: "HappyFace.jpg"
 };
 s3.deleteObject(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
   /*
   data = {
   }
   */
 });
Run Code Online (Sandbox Code Playgroud)