nervgh / angular-file-upload

[ALMOST NOT MAINTAINED] Angular File Upload is a module for the AngularJS framework
MIT License
3.44k stars 1.13k forks source link

Adding an image captured via camera #890

Closed tschofen closed 2 years ago

tschofen commented 2 years ago

I'm trying to add an image to an uploader.queue that was captured via computer camera. I captured the image from a canvas convert it into a blob (instance of Blob is true at that point) and pass it into the uploader instance;

I then render the queue with ng-thumb. Unfortunately, ng-thumb can't render the preview as it doesn't recognize the created blob as a blob or as a file (instanceof Blob or instanceof File are both false) and therefore never finishes drawing the preview.

Any idea how I can make the captured file render for the preview?

The salient Javascript parts.

var uploader = $scope.uploader = new FileUploader({url: 'upload.php'});
var data = canvas.toDataURL('image/png');
var file = blobToFile(dataURItoBlob(data), 'snapshot');
console.log('Is it a blob?', file instanceof Blob) //returns true

uploader.addToQueue(file);

function blobToFile(theBlob, fileName) {
  //A Blob() is almost a File() - it's just missing the two properties below which we will add
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}

function dataURItoBlob(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var array = [];
  for(var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {type: mimeString});
};

And the HTML:

 <div ng-repeat="item in uploader.queue">
       <div class="uploader-item-thumb" ng-thumb="{ file: item._file, width:155 }"></div>
 </div>
tschofen commented 2 years ago

Turns out, that the issue is that the generated Blob object must be cast to a File object and that only seems to work when most of the File properties are properly set. This did the trick...

function blobToFile(theBlob, fileName) {
  return new File([theBlob], fileName,{ lastModified: new Date().getTime(), type: theBlob.type })
}