我正在尝试从文件夹中获取图像文件名,以将它们作为 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 = "<img src=\"img\/gallery\/" + val + "\">";
$("#lightbox").append(lightboxElement);
}
});
},
error: function(exception) {
console.log(data);
}
});
基本上,这段代码的作用是在指定文件夹中搜索不同类型的图像文件并返回它们的名称。然后,将具有图像源地址的 img 元素添加到确定的 HTML 对象 (#lightbox)。
当我在本地服务器上运行整个项目时,它工作得很好。但是,当将其上传到 AWS S3 存储桶时,该 ajax 调用不起作用。当我搜索时,我发现了一些可能的解决方案。
1) 他们建议将跨域资源共享 (CORS) 文件添加到存储桶中。我使用以下规则添加了该文件。但没有成功。
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
2) 在S3存储桶选项中,有“公开”选项。我对“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.<anonymous> (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 个对象(但请注意,前缀
中没有前导 /
)。
这是列表对象 V1 API。对于匿名访问,您不需要任何 AWS 库...但您需要解析 XML 并处理分页。
http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
还有一个 V2 API,在上面的页面中也提到过。
关于jquery - 如何对AWS S3存储桶进行ajax调用以从文件夹中获取文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41251450/