Append image file to form data - Cordova/Angular

25,995

Solution 1

After some fiddling around I manage to figure out a pretty simple solution. First I added the cordova file plugin then I use the code below

var fd = new FormData();
     window.resolveLocalFileSystemURL(attachment.img, function(fileEntry) {
         fileEntry.file(function(file) {
             var reader = new FileReader();
                 reader.onloadend = function(e) {
                      var imgBlob = new Blob([ this.result ], { type: "image/jpeg" } );
                      fd.append('attachment', imgBlob);
                      fd.append('uuid', attachment.uuid);
                      fd.append('userRoleId', 12345);
                      console.log(fd);
                      //post form call here
                 };
                 reader.readAsArrayBuffer(file);

         }, function(e){$scope.errorHandler(e)});
    }, function(e){$scope.errorHandler(e)});

So I'm just creating a form and using FileReader to insert an ArrayBuffer to the Blob object and then append that to the form data. Hopefully this helps someone else looking for an easy way to do this.

Solution 2

You do need to send file content. With the HTML5 FileAPI you need to create a FileReader object.

Some time ago, I developed an application with cordova and I had to read some files, and I made a library called CoFS (first, by Cordova FileSystem, but it's working in some browsers).

It's on beta state, but I use it and works well. You can try to do some like this:

var errHandler = function (err) {
   console.log("Error getting picture.", err);
};

var sendPicture = function (file) {

    var fs = new CoFS();

    fs.readFile(file, function (err, data) {

        if (err) {
            return errHandler(err);
        }

        var fd = new FormData();

        fd.append('attachment', new Blob(data));
        fd.append('uuid', uuid);
        fd.append('userRoleId', userRole);

        console.log("Data of file:" + data.toString('base64'));
        // Send fd...

    });

};

navigator.camera.getPicture(sendPicture, errHandler);

Sorry my poor english.

Share:
25,995

Related videos on Youtube

Joe Komputer
Author by

Joe Komputer

Updated on July 10, 2022

Comments

  • Joe Komputer
    Joe Komputer almost 2 years

    I am using Anuglar, Ionic and Cordova in my current project, and I'm trying to POST FormData containing an image file to my server. Right now I'm using the cordova camera plugin to return a file path to the image on the device (ex: file://path/to/img). Once I have the file path I want to append the image file to a FormData object using the images file path. Here is my code right now.

    var fd = new FormData();
    
    fd.append('attachment', file);
    fd.append('uuid', uuid);
    fd.append('userRoleId', userRole);
    

    The code above works when appending a file that is taken from an <input type='file'> but doesn't work when just given the file path on the device.

    Basically the FormData is showing like this right now:

    ------WebKitFormBoundaryasdf
    Content-Disposition: form-data; name="attachment"; 
    
    file://path/to/img
    

    and I want it to look like this

    ------WebKitFormBoundaryasdf
    Content-Disposition: form-data; name="attachment"; filename="jesus-quintana.jpg"
    Content-Type: image/jpeg
    

    I found many different ways to upload the image using cordova FileTransfer and by converting the image to a base64 and then uploading it. But I couldn't find any simple ways of just grabbing the file by using the path and posting it within a form. I'm not very familiar with the File Api so any help would be appreciated

  • Dave Rael
    Dave Rael almost 9 years
    Beautiful. Nicely done, @Joe Komputer. This is exactly what I sought.
  • Eric Hodonsky
    Eric Hodonsky over 8 years
    I'd been avoiding doing this because I was unsure how my server would handle the blob... but apparently it was no issue. Thanks!!
  • Amr.Ayoub
    Amr.Ayoub over 7 years
    Hello , can you share the html code along with js. Thanks :)
  • Joe Komputer
    Joe Komputer about 7 years
    It's been awhile since I wrote this code but I believe attachment.img was a string with the value of the local images path. So something like "file://your/images/path". This link may help here @KiranReddy
  • tonejac
    tonejac over 6 years
    This answer rocked! Nice work. In my case I didn't even need the FormData(), only needed the FileReader() and used the Blob() to upload the image to my server. stackoverflow.com/questions/47003749/…
  • desmeit
    desmeit over 5 years
    Hey, I tried your code but reader.onloadend is not fireing. Do you have an idea what could be the problem? Thanks
  • jtate
    jtate over 2 years
    Be aware that this reads the entire file into memory before posting to the server. For large files this can be slow and potentially crash your application if there is not enough memory available.