Load Image Data into Angularjs
Asked Answered
S

2

1

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

Slalom answered 17/12, 2013 at 17:33 Comment(0)
C
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.

Cioffi answered 17/12, 2013 at 17:52 Comment(0)
B
0

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
}
Banka answered 17/12, 2013 at 18:0 Comment(1)
You might be able to then still get the image data using a canvas element, https://mcmap.net/q/17064/-get-image-data-url-in-javascriptKeeter

© 2022 - 2024 — McMap. All rights reserved.