如何对AWS S3存储桶进行ajax调用以从文件夹中获取文件名?

我试图从文件夹中获取图像文件名,以将其作为HTML元素动态添加到我的网页。 为了做到这一点,我发现这段代码在本地主机上完美运行。

var folder = "img/gallery/"; $.ajax({ url: folder, success: function(data) { $(data).find("a").attr("href", function(i, val) { if (val.match(/\.(jpe?g|png|gif)$/)) { // TODO: Filter and Title strings needs to be changed var lightboxElement = ""; $("#lightbox").append(lightboxElement); } }); }, error: function(exception) { console.log(data); } }); 

基本上,这段代码的作用是在指定的文件夹中搜索不同类型的图像文件并返回它们的名称。 然后,将具有图像源地址的img元素添加到确定的HTML对象(#lightbox)。

当我在我的本地服务器上运行整个项目时,它完全正常。 但是,将其上载到AWS S3存储桶时,该ajax调用不起作用。 当我搜索时,我找到了几种可能的解决方案。

1)他们建议将交叉源资源共享(CORS)文件添加到存储桶中。 我添加了以下规则的文件。 但它没有用。

    * GET *   

2)在S3存储桶选项中,有“Make Public”选项。 我对“img”和“gallery”文件夹都使用了该选项,但它没有用。

3)有人建议使用Amazon Route53 CNAME作为文件夹的路径,如下所示。

 var folder = "http://example.com.s3-website-us-east-1.amazonaws.com/img/gallery/"; 

这也行不通。

最后,您可以在下面找到我加载页面时收到的两条错误消息。

 1) Failed to load resource: the server http://example.com/img/gallery/ responded with a status of 404 (Not Found) 2) Uncaught ReferenceError: data is not defined at Object.error (custom.js:21) at i (jquery.min.js:2) at Object.fireWith [as rejectWith] (jquery.min.js:2) at z (jquery.min.js:4) at XMLHttpRequest. (jquery.min.js:4) 

此外,您可以在下方的Chrome检查的“网络”标签中找到返回的消息。

 Code: NoSuchKey Message: The specified key does not exist. Key: img/gallery/index.html RequestId: KSDJGSL3405309lkjLKJ087944GHFG654hJHGjhk8979 HostId: LD0349823= An Error Occurred While Attempting to Retrieve a Custom Error Document Code: NoSuchKey Message: The specified key does not exist. Key: error.html 

提前致谢!

我强烈建议不允许公开列出存储桶内容,但如果这是你的意图,这是解决方案:

使用存储桶的REST端点( 而不是网站端点)(例如https://example-bucket.s3.amazonaws.com ),您的URL看起来像这样 – 为了清晰起见,添加了换行符。

 https://example-bucket.s3.amazonaws.com/ ?prefix=img/gallery/ &delimiter=/ 

这将返回/img/gallery下的前1000个对象(但请注意prefix没有前导/ )。

这是List Objects V1 API。 对于匿名访问,您不需要任何AWS库……但您需要解析XML并处理分页。

http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html

还有一个V2 API,也在上面的页面中提到过。