简体   繁体   English

如何使用ajax get rest api从aws s3中获取对象

[英]How to fetch object from aws s3 using ajax get rest api

I have a file named 3514706-ironmanvr-promo-nologo.jpg in my s3 bucket and I am trying to download the file using javascript rest api, here is my code我的 s3 存储桶中有一个名为3514706-ironmanvr-promo-nologo.jpg的文件,我正在尝试使用 javascript rest api 下载该文件,这是我的代码

var jqxhr = $.ajax({
            url: "https://s3.amazonaws.com/asif.test/3514706-ironmanvr-promo-nologo.jpg",
            type: "GET",
            async: true
        })
            .done(function (data, textStatus, jqXhr) {
               console.log(data);

            })
            .fail(function (jqXhr, textStatus, errorThrown) {
                console.log(errorThrown);
                if (errorThrown === "abort") {
                    alert("Uploading was aborted");
                } else {
                    alert("Uploading failed");
                }
            })
            .always(function (data, textStatus, jqXhr) { });

but in data I am getting garbage values like this但在数据中我得到这样的垃圾值

response image回应图片

I don't know how to deal with this.我不知道如何处理这个。

I was having the exact same issue, and after much digging and hair-removal I came across this answer:我遇到了完全相同的问题,经过多次挖掘和脱毛后,我发现了这个答案:

https://medium.com/@timleland/set-image-src-from-amazon-s3-2232d246bebd https://medium.com/@timleland/set-image-src-from-amazon-s3-2232d246bebd

It solved it for me;它为我解决了; the article says:文章说:

"Since Jquery ajax does not support the responseType: 'blob', you have to set the value in the xhrFields. The other important part is to use window.URL.createObjectURL to convert the blob to a url for the image src." “由于 Jquery ajax 不支持 responseType: 'blob',您必须在 xhrFields 中设置值。另一个重要部分是使用 window.URL.createObjectURL 将 blob 转换为图像 src 的 url。”

 var loadImage = function (imageUrl) { $.ajax({ type: 'GET', url: imageUrl, dataType: null, data: null, xhrFields: { responseType: 'blob' }, success: function (imageData) { var blobUrl = window.URL.createObjectURL(imageData); $('#image-id').attr('src', blobUrl); } }); };

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

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