简体   繁体   中英

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

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

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."

 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); } }); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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