Get image data from another domain with AJAX request

…衆ロ難τιáo~ 提交于 2019-12-11 09:54:30

问题


I am trying to get binary data of an image from another domain with an AJAX request. I tried various methods, but there was no working solution. I found some code on the internet that looked good, but even with this calls I get errors.

What do I wrong? Is there a standardized way to do this?

Here is what I tried until now:

var request = this.createCORSRequest('GET', 'http://url/to/image.png');
request.onload = function () {
    var text = request.response;
};
request.onerror = function (error) {
    alert('Woops, there was an error making the request.');
};

request.send();

private createCORSRequest(method, url) {
        var xhr: XMLHttpRequest = new XMLHttpRequest();
        if ("withCredentials" in xhr) {

        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.open(method, url, true);

        } else if (typeof XDomainRequest != "undefined") {

            // Otherwise, check if XDomainRequest.
            // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
            var xdhr = new XDomainRequest();
            xdhr.open(method, url);

        } else {

            // Otherwise, CORS is not supported by the browser.
            xhr = null;

        }
        return xhr;
}

I even found this solution without ajax here on stackoverflow, but it does not work for me:

Asynchronously load images with jQuery

Here a screen of the properties the error event contains:

My goal is to get the binary of an image from a url which I get from an atom feed . I need the binaries to copy the picture to MS SharePoint.


回答1:


You cannot get data from another domain unless :

  • the remote server allows it using CORS
  • you run your browser in an unsafe mode.

Reason : otherwise site A would be able to (maliciously) read the user data from site B




回答2:


You must add headers to the method to allow cross domain request. For example, if you are trying to get data from www.example.com/main.php , then you must add headers to allow those method to be called from different domain.



来源:https://stackoverflow.com/questions/30025343/get-image-data-from-another-domain-with-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!