get image file object from url

10,329

Solution 1

$http.get("image_url", {responseType: "arraybuffer"}).success((data) => {
    fd.append('file', data);
});

It's a general idea, when you get your image url, just make a request as arraybuffer to the URL, then you just have to pass the blob object to your formdata.

Solution 2

Convert a image from the given url into a file object:

$http.get(url,{responseType: "blob"}).success((data) => {
  var file = new File([data], "sample.jpg");
  $scope.sampleFile=file;
});
Share:
10,329
Gaurav Gupta
Author by

Gaurav Gupta

Senior Undergrad at IIT (BHU) Varanasi. Loves deep learning.

Updated on June 04, 2022

Comments

  • Gaurav Gupta
    Gaurav Gupta about 2 years

    I am making a django-angularjs webapp. There is a option for file uploading for the users.

    I want to provide users with some sample images to upload.
    So it will be like the sample images will be sent by server to client and again send back to the server if the client chooses them as Fresh upload.

    angularjs directive:

    angular.module('users').directive('fileModel', ['$parse', function ($parse) {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;
    
        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
    };
    }]);
    

    my html:

    <input type="file" file-model="myFile"/><br><br>
    <button ng-click="uploadFile()">Upload</button>
    

    angular-js controller:

    $scope.uploadFile = function(){
    
        var file = $scope.myFile;
        var uploadUrl = "/multer";
        var fd = new FormData();
        fd.append('file', file);
    
        $http.post(uploadUrl,fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
          console.log("success!!");
        })
        .error(function(){
          console.log("error!!");
        });
    };
    

    Using the code above the user can select the image from their pc and upload them.

    Now if we have the url for the sample images sent by server. How to code the angular controller to get images for their file object from those urls?
    like $scope.myFile=getImageFileObjectFromUrl(url) ??

    thanks for help

  • Gaurav Gupta
    Gaurav Gupta over 8 years
    Not working... data is always empty arraybuffer. although i can see the jpeg data when i remove the response type.
  • Maël Lavault
    Maël Lavault over 8 years
    Which release of angular do you use ?
  • Maël Lavault
    Maël Lavault over 8 years
    You will have to use XHR2 to make arraybuffer work, so maybe just use a raw XMLHttpRequest 2 instead of angular's $http.
  • TheCleverIdiot
    TheCleverIdiot almost 7 years
    Hi, any idea about displaying this image to HTML side?