Load Image Data into Angularjs

偶尔善良 提交于 2019-12-08 04:18:22

问题


I have a bunch of image urls and I want to download the images from the browser into a zip file. I'm planning on using jszip to create the zip file. And I have all the image urls from the server. What I attempted was :

var img = zip.folder("profiles");



async.mapSeries($scope.queriedUsers, 
    function (user, iterCallback) {

        delete $http.defaults.headers.common['X-Requested-With'];
        $http.get(user.profile_image_url, {responseType: "arraybuffer"})
            .success(function (data) {
                iterCallback(null, {data: data, name: user.screen_name});
            })
            .error(function (data, status) {
                iterCallback(status, data);
            })

        },
    function (err, results) {
        _.each(results, function (result){
            img.file(result.screen_name + ".gif", result.data, {base64: true});
        });

        var content = zip.generate();
        window.location.href = "data:application/zip;base64," + content;
    });

And the error i got was:

OPTIONS <url> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

What I find interesting is that in the html the images load fine:

<tbody>
    <tr ng-repeat="user in queriedUsers">
        <td><a href="https://twitter.com/{{user.screen_name}}"><img ng-src="{{user.profile_image_url}}" alt="User Twitter Image"></a></td>
        <td><a href="https://twitter.com/{{user.screen_name}}">{{user.screen_name}}</a></td>
        <td>{{user.name}}</td>
        <td>{{user.description}}</td>  
    </tr>
</tbody>

How do I load the image data into angularjs? Is there a way to get it directly for the ng-src?

Thanks


回答1:


Basically you have a cross domain issue here. You can open images with remote URL but you cannot make Ajax request to a different domain than yours. Please take a look here: http://en.wikipedia.org/wiki/Same-origin_policy

You can overtake this problem by creating a proxy. This means that your Ajax request would be pointing to your server and at the response you could send the image address, which can be used normally afterwards.




回答2:


You can't make ajax calls to different domains without using CORS.

BUT if you only need the actual image, you can just do the following:

// Create image object
var img = document.createElement("img");

// Set source to profile image url
img.src = user.profile_image_url;

// Wait for image to load
img.onload = function(){
  // Callback
}


来源:https://stackoverflow.com/questions/20640920/load-image-data-into-angularjs

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