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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.