Help to POST results from camera to API


#1
var options = {
          quality: 50,
          allowEdit: true,
          targetWidth: 100,
          targetHeight: 100,
          encodingType: "jpeg",
          saveToPhotoAlbum: false,
          //destinationType: "dataURL"
        };
        supersonic.media.camera.takePicture(options).then( function(result){

I want to take the result and POST it to an API that is expecting a file. like “image.jpg”

with something like this:

$http({
                url: config.api + '/attachment/file',
                method: "POST",
                headers: {
                    'Authorization': "Bearer " + app.session.getToken(),
                    'api-key': config.apiKey,
                    company: localStorage.getItem('user_company'),
                    'Content-Type':  undefined
                   
                },
                transformRequest: angular.identity,
                data: formData
            }).then(function successCallback(response) {

I’m having a heck of a time getting the file created/set right. I’m tried a handful of methods, and I am wondering if it’s me or the results that are coming back. Could some one point me to a recent example? Or offer something to try?


#2

Part of my issue was that I assumed that the Base64 string would include data:image/jpg;base64. make sure you prepend that to the string returned.

then you can use something like this:

function dataURItoBlob(dataURI) {
          // convert base64 to raw binary data held in a string
          // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
          var byteString = atob(dataURI.split(',')[1]);

          // separate out the mime component
          var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

          // write the bytes of the string to an ArrayBuffer
          var ab = new ArrayBuffer(byteString.length);
          var ia = new Uint8Array(ab);
          for (var i = 0; i < byteString.length; i++) {
              ia[i] = byteString.charCodeAt(i);
          }

          // write the ArrayBuffer to a blob, and you're done
          var blob = new Blob([ab], {type: mimeString});
          return blob;

          // Old code
          // var bb = new BlobBuilder();
          // bb.append(ab);
          // return bb.getBlob(mimeString);
        };

and then

var imageToPost = dataURItoBlob(imageGotten);
var formData = new FormData();
formData.append('file', imageToPost, fileName);

hope it helps someone else.