Search code examples
ng-file-upload

use blob data from server with ng-file-upload?


I have a use case where after images are uploaded with ng-file-upload, the server is now in processes of generating thumbnails and on request, return a base64string of the file (the thumbnail, very small like 2K).

This is working quite well; however, I would also then like to be able to use that blob with ng-file-upload in other uses such as with ngf-src or ngf-background. But i'm not sure how exactly.

I'm currently using this to request and generate the blob (controller shortened for brevity):

$http({
    url: appconfig.serviceUrl + ":" + appconfig.port + "/api/file/" + fileName,
    method: 'GET',
    cache: true,
    headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
    var apiURL = (window.createObjectURL && window) || (window.URL && URL.revokeObjectURL && URL) || (window.webkitURL && webkitURL);
    var blob = new Blob([response.data], { type: 'image/jpg' });
    blob.src = response.data;
    blob.url = apiURL.createObjectURL(blob);
    deferred.resolve(blob);
}, function (error) {
    deferred.reject(error);
}));

In my HTML partials, I can use the following to easily show the blob in any browser (where controlleras is 'vm' and the blob eventually gets into vm.img for the scope):

<img ng-src="data:image/jpg;base64,{{vm.img.src}}" type="image/jpg" width="320" height="180"/>

I realize this may not be the right format for a blob, I'm just learning to use them.

I tried doing something like the following:

var file = new File([blob], fileName, { type: 'image/jpg' });

While Chrome and FireFox seemed to be able to generate the file ok, IE11 would throw a "TypeError: Object doesn't support this action"...

How can I now create a 'file' for use in ng-models for ng-file-upload to consume and work with?

On another note, at first I was able to just send the file as stream from the server on request.. however, it was a native file (byte array?) with exif data. I could 'not' figure out to use that with ng-file-upload either :(


Solution

  • You can just have a string for ngf-src or ngf-background so there is no need for converting the dataurl to Blob. You can have something like this:

    ngf-src="fileBlob || fileDataUrlString"
    

    It is generally better to keep the url string and actual blob file that is selected by browser separately since you cannot really set the value of the file input programmatically because of the security concerns of the browser.