Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append image file to form data - Cordova/Angular

Tags:

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

like image 471
Joe Komputer Avatar asked Mar 03 '15 23:03

Joe Komputer


1 Answers

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.

like image 176
Joe Komputer Avatar answered Sep 21 '22 23:09

Joe Komputer