简体   繁体   English

如何在React JS中从S3存储桶中获取5个最新文件?

[英]How to get 5 latest files from s3 bucket in react js?

I am using aws-sdk to get object list as below: 我正在使用aws-sdk来获取对象列表,如下所示:

 const AWS = require('aws-sdk/global');

 const S3 = require('aws-sdk/clients/s3');

 AWS.config.update({ accessKeyId: 'abc123', secretAccessKey: 'teyb3872312', region: 'eu-west-1' });
 const s3 = new AWS.S3();

const params = {
  Bucket: 'demo-bucket',
  Delimiter: '',
  Prefix: '',
};

  s3.listObjectsV2(params, (err, data) => {
  if (err) throw err;
  console.log(data.Contents);
 })

From this code i am getting all thousand objects from the bucket, but want only 5 latest object from the bucket. 从这段代码中,我从存储桶中获取了所有数千个对象,但只希望从存储桶中获得5个最新对象。

Please suggest if anyone know the solution. 请建议是否有人知道解决方案。

It is not possible to request a listing based upon LastModified . 无法基于LastModified请求列表。

Instead, your application will need to retrieve the entire list, then sort the objects returned by LastModified and then select the newest 5. 相反,您的应用程序将需要检索整个列表,然后对LastModified返回的对象进行排序,然后选择最新的5。

Also, please note that a maximum of 1000 objects will be returned per call. 另外,请注意,每次调用最多返回1000个对象。 You will need to use the Continuation Token to request the next 1000 objects, and keep repeating until the listing is complete. 您将需要使用Continuation Token来请求下一个1000个对象,并不断重复直到列表完成。

If you will be doing this on a regular basis, you might also consider using Amazon S3 Inventory , which can provide a daily listing of all objects in a bucket. 如果您要定期执行此操作,则还可以考虑使用Amazon S3库存 ,它可以提供存储桶中所有对象的每日列表。

S3 doesn't allow to sort objects by last modified date, so you need to fetch all object and then sort it in your code. S3不允许按上次修改日期对对象进行排序,因此您需要获取所有对象,然后在代码中对其进行排序。

It might cause a performance issue in case of large buckets. 如果存储桶较大,可能会导致性能问题。

In order to avoid this, you should store object's creation date in some database after upload. 为了避免这种情况,您应该在上传后将对象的创建日期存储在某个数据库中。 You can do it from your code or subscribe to S3 Events and track PUT operations (see https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html ) 您可以从代码中完成操作,或者订阅S3事件并跟踪PUT操作(请参阅https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM