How to show image from blob url and download file in AngularJS

Posted By : Prerna Jajoria | 30-Jun-2015

1. If we have response data in blob data then we can easily download it.

A function is given here to do the same:

$scope.downloadAttachment = function(fileData){
         var downloadAttachmentJson = fileData;
        toolingService.attachementDownload(downloadAttachmentJson,function(jsonAttachmentDownload) {
            var blob=new Blob([jsonAttachmentDownload], {type: "octet/stream"});
            var url = URL.createObjectURL(blob);
            
           if (navigator.appVersion.toString().indexOf('.NET') > 0){
                window.navigator.msSaveBlob(blob, fileName); // For IE browser
            }else{
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                blob = new Blob([jsonAttachmentDownload], {type: "octet/stream"}),
                a.href = window.URL.createObjectURL(blob);  // For chrome,firefox,opera and safari
                a.download = "fileName";
                a.click();
            }
        });
    };

 

2. Show image for given blob url.

We use blob data very often to show images. But when we try to use it in angularJs it throws error of unsafe data. Actually angularJs append a prefix "unsafe :" with it due to security reasons and it results into a broken image. Only http,https,ftp and mailto are enabled by default.

So for this, We can do one thing. The fix is given here:

This regex just allow blob url.

 

myModule.config(['$compileProvider', function($compileProvider) {
  $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob):|data:image\//);
});

THANKS

About Author

Author Image
Prerna Jajoria

Prerna is a bright Java developer with skills is Groovy and Grails , Play frameworks etc . Other than programming her interests are music and dancing.

Request for Proposal

Name is required

Comment is required

Sending message..