octet stream download as csv doesn't work in IE [duplicate] - javascript

I have this in my Angular.js controller that downloads a CSV file:
var blob = new Blob([csvContent.join('')], { type: 'text/csv;charset=utf-8'});
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
This works perfectly in Chrome but not in IE. A browser console log says:
HTML7007: One or more blob URLs were revoked by closing the blob for
which they were created. These URLs will no longer resolve as the data
backing the URL has been freed.
What does it mean and how can I fix it?

Try this using, this or useragent
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(blob, filename);
else
{
var blob = new Blob(['stringhere'], { type: 'text/csv;charset=utf-8' });
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
}

IE won't allow you to open blobs directly. You have to use msSaveOrOpenBlob. There's also msSaveBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}

I needed to use a Blob to download a converted a base64 PNG image. I was able to successfully download the blob on IE11 with window.navigator.msSaveBlob
See the following msdn link:
http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Specifically, you should call:
window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');
where blobObject is a Blob created in the usual fashion.

Complete Solution for Chrome, Internet Explorer Firefox and Opera
There are lots of nice bits on this page, but I had to use a combination of a few things to get it all to work. Hopefully this helps you.
Use a button or link to trigger a function called download():
<button class="button-no save-btn" ng-click="download()">DOWNLOAD</button>
Put this in your controller:
$scope.download = function () {
// example shows a JSON file
var content = JSON.stringify($scope.stuffToPutInFile, null, " ");
var blob = new Blob([content], {type: 'application/json;charset=utf-8'});
if (window.navigator && window.navigator.msSaveBlob) {
// Internet Explorer workaround
$log.warn("Triggering download using msSaveBlob");
window.navigator.msSaveBlob(blob, "export.json");
} else {
// other browsers
$log.warn("Triggering download using webkit");
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create invisible element
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', url);
downloadLink.attr('download', 'export.json');
// make link invisible and add to the DOM (Firefox)
downloadLink.attr('style','display:none');
angular.element(document.body).append(downloadLink);
// trigger click
downloadLink[0].click();
}
};

What's your IE browser version? You need a modern browser or IE10+
http://caniuse.com/bloburls

Maybe you need some delay. What about with:
link.click();
setTimeout(function(){
document.body.createElementNS('http://www.w3.org/1999/xhtml', 'a');
URL.revokeObjectURL(link.href);
}, 100);

I needed to get the download feature to work in Chrome and IE11. I had good success with this code.
HTML
<div ng-repeat="attachment in attachments">
<a ng-click="openAttachment(attachment)" ng-href="{{attachment.fileRef}}">{{attachment.filename}}</a>
</div>
JS
$scope.openAttachment = function (attachment) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(
b64toBlob(attachment.attachment, attachment.mimeType),
attachment.filename
);
}
};

Done it this way, working fine for me.
downloadFile(data) {
if (navigator.msSaveBlob) {
let blob = new Blob([data], {
"type": "text/csv;charset=utf8;"
});
navigator.msSaveBlob(blob, this.fileName);
}
else {
let blob = new Blob(['\ufeff' + data], { type: 'text/csv;charset=utf-8;' });
let $link = document.createElement("a");
let url = URL.createObjectURL(blob);
$link.setAttribute("target", "_blank");
$link.setAttribute("href", url);
$link.setAttribute("download", this.fileName);
$link.style.visibility = "hidden";
document.body.appendChild($link);
$link.click();
document.body.removeChild($link);
}
}

Try to use this instead :
var blob = file.slice(0, file.size);

Create polyfill method as below,had a variable filename since in my case download filename was static.This method will be called while blob function is not supported as in case of Internet explorer
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype,
'toBlob', {
value: function (callback, type, quality) {
var canvas = this;
setTimeout(function () {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
var blob = new Blob([arr], {
type: 'image/png'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
});
}
});
}

try {
const blob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
const file = new File([blob], this.getFileName(res), {
type: res.headers.get('Content-Type'),
});
saveAs(file);
} catch (err) {
var textFileAsBlob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
window.navigator.msSaveBlob(textFileAsBlob, this.getFileName(res));
}
To get the file name. Use the below function.
getFileName(response: any) {
let name: string;
try {
const contentDisposition: string = response.headers.get(
'content-disposition'
);
const [, filename] = contentDisposition.split('filename=');
name = filename;
} catch (e) {
name = 'File_Name_Not_Specified_' + new Date();
}
return name;
}
This worked for me.

Related

Handling stream from server and displaying the file in browser

I'm trying to find the global solution for handling strem files from the server.
My response object is angular http Response
My object has differnet _body for images/docs etc.
images is a long string of ##$.. and docs are json
I've been looking for solutions over the web, and got to implement this:
let contentType = resData.headers.get("Content-Type");
let blob = new Blob([resData.arrayBuffer()], {type: contentType});
let url = window.URL.createObjectURL(blob);
window.open('url: ', url);
This code downloads a file that has content-type of octet-stream
but all other files are not displayed in the browser.
My main goal is to have the same behavior if would have put in the URL the API that returns a stream, and the browser knows how to handle it (images are shown in browser, files that browser doesn't support are automatically downloaded etc.)
This is the code for the request.
return Observable.create(observer => {
let xhr = new XMLHttpRequest();
xhr.open(Object.keys(RequestMethod).find(k => RequestMethod[k] === url.method), url.url, true);
const shift =
xhr.setRequestHeader('Content-type', 'application/json');
xhr.responseType = (Object.keys(ResponseContentType).find(k => ResponseContentType[k] === url.responseType)).toLocaleLowerCase();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let blob = new Blob([xhr.response], {type: body.MimeType});
observer.next({blob: blob, fileName: body.FileName});
observer.complete();
} else {
observer.error(xhr.response);
}
}
}
xhr.send(url.getBody());
This is the code for the special handling of each mimeType
handleAttachmentItem(resData) {
let blob = resData.blob;
const fileName = resData.fileName;
if (blob.type.includes('image')) {
let b64Response = window.URL.createObjectURL(blob);
let outputImg = document.createElement('img');
outputImg.src = b64Response;
let w = window.open();
w.document.write('<html><head><title>Preview</title><body style="background: #0e0e0e">');
w.document.write(outputImg.outerHTML);
} else if (blob.type.includes('text')) {
let url = window.URL.createObjectURL(blob);
window.open(url);
} else {
let a = document.createElement("a");
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
}

CSV Export of Table in Chrome Not Working - JavaScript/AngularJS

I'm currently working on fixing a CSV Export of a data table on a web application.
It's currently able to export on all needed browsers except Chrome when you click the export button.
I've been trying to figure it out for a while now and I'm resisting pulling my hair out.
The code below is my service that was working until recently. Any help is greatly appreciated.
svc.downloadContent =
(target, fileName, content) => {
if (!browserSvc.canDownloadFiles()) return;
// IE10
if (window.navigator.msSaveOrOpenBlob) {
const blob = new Blob([content], {type: 'text/csv'});
window.navigator.msSaveOrOpenBlob(blob, fileName);
// IE9
} else if (env.browser === 'Explorer') {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
angular.element(frame).hide();
const cw = frame.contentWindow;
const cwDoc = cw.document;
cwDoc.open('text/csv', 'replace');
cwDoc.write(content);
cwDoc.close();
cw.focus();
cwDoc.execCommand('SaveAs', true, fileName);
document.body.removeChild(frame);
// Sane browsers
} else {
const blob = new Blob([content], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const a = angular.element(target);
const download = a.attr('download');
// If not already downloading ...
if (!download) {
a.attr('download', fileName);
a.attr('href', url);
// This must run in the next tick to avoid
// "$digest already in progress" error.
//$timeout(() => target.click());
try {
target.click();
// Clear attributes to prepare for next download.
a.attr('download', '');
a.attr('href', '');
} catch (e) {
console.error('csv-svc.js: e =', e);
}
}
}
I managed to figure this out just a couple minutes after posting my question. I needed to add an else if just for Chrome. However, I will post the fix and leave this up, in hopes that it may help someone else in the future.
else if (env.browser === 'Chrome') {
const blob = new Blob([content], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.style = 'visibility:hidden';
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

MVC Asp.net zip file download

I have some code in an MVC project that creates a zip file and sends it to the browser. Everything works when I manually enter the URL in the browser, but if I click on the link in the page to get the download, I get a file of a different size and Windows cannot open it.
So, if I manually enter something like this:
http://localhost/fms-ui/File/DownloadZipFile/?id=10&filename=DST-2015-11-14_04_04_04
I get a zip file of 167 bytes and it open fine.
If I click on the link in the page, I get a file of 180 bytes and Windows says the file is corrupted. Hun?
My one stipulation is that I cannot use an external library. Due to politics I must use the library provided with .Net Framework 4.5 (static ZipFile class).
Code:
public FileContentResult DownloadZipFile(int id, string filename)
{
/*
* 1 - get fileset info
* 2 - get temp file name
* 3 - create zip file under temp name
* 4- return file
*/
QuesterTangent.Wayside.FileServices.FileSet sInfo = new QuesterTangent.Wayside.FileServices.FileSet(id);
string path = Path.Combine(sInfo.BasePath);
string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".zip");
ZipFile.CreateFromDirectory(path, tempPath);
byte[] fileBytes = System.IO.File.ReadAllBytes(tempPath);
//System.IO.File.Delete(tempPath); Commented so I can compare the files
filename = filename + ".zip";
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileBytes, "application/zip");
}
I've tried this with and without AppendHeader and with various contentTypes, but it doesn't seem to effect the outcome.
Here is the JavaScript that calls the controller (I inherited this code but it works for other things).
function GetFile(url) {
//spin a wheel for friendly buffering time
var buffer = $('.MiddleRightDiv').spinBuffer();
$.ajax({
url: url,
type: "POST",
cache: false,
async: true,
data: {},
success: function (response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
complete: function (result) {
if (typeof $('.MiddleRightDiv').spinBuffer !== 'undefined' && $.isFunction($('.MiddleRightDiv').spinBuffer)) {
$('.MiddleRightDiv').spinBuffer("destroy");
}
}
});
Any input would be a great help. I have gone over other similar postings but non of them seems to address the core problem I am having.
Thanks,
dinsdale
jQuery.ajax cannot read bytestreams correctly (check SO for many topics about this), so we have to use old and good XMLHttpRequest. Here is your function refactored to work with blobs. Extened it with fallbacks for other browsers while saveAs(blob,filename) is the draft.
function GetFile(url) {
if (window.navigator.msSaveBlob) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
req.onload = function (e) {
if (req.response) {
var filename = 'archive.zip';
var disposition = req.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = req.getResponseHeader('Content-Type');
var blob = new Blob([req.response], { type: type ? type : 'application/octet' });
window.navigator.msSaveBlob(blob, filename);
} else {
throw 'Empty or invalid response';
}
}
req.send();
} else {
//fallback for browsers without blob saver
throw 'Not implemented';
}
}

Blob constructor Safari issue

I am using JQuery blob to export the JQuery array to CSV.
It is working on every browser except on Safari 5.1.7.
Safari browser on Windows 7.
I came to Know Blob has compatibility issues with Safari.
please let me know if there is any work around to achieve it.
Below is the code:
var usersCSVData = [];
usersCSVData.push('LastName ','FirstName ', 'Login ','City ','State','Location ');
var fileName = "UserCSVdata.csv";
var buffer = usersCSVData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, fileName);
}
else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
I am getting error:
"'[object BlobConstructor]' is not a constructor (evaluating 'new Blob([buffer], {
"type": "text/csv;charset=utf8;"
})')"
Try to use BlobBuilder or WebKitBlobBuilder first. Also such using blob constructors/builders solve some problems in Android Stock Browser 4.4-:
//cross browser BlobBuilder constructor
var customBlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder;
//result
var blob;
//Data
var buffer = ['LastName ','FirstName ', 'Login ','City ','State','Location '].join("\n");
//Try to use WebKitBlobBuilder first, It also solves some issues for Android Stock Browser
if (window.WebKitBlobBuilder) {
blob = new WebKitBlobBuilder();
blob.append(buffer);
blob = blob.getBlob("text/csv");
} else if (window.Blob) {
blob = new Blob([buffer], { type : "text/csv" });
} else {
blob = new customBlobBuilder();
blob.append(buffer);
blob = blob.getBlob("text/csv");
}
console.log(blob);

Blob download is not working in IE

I have this in my Angular.js controller that downloads a CSV file:
var blob = new Blob([csvContent.join('')], { type: 'text/csv;charset=utf-8'});
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
This works perfectly in Chrome but not in IE. A browser console log says:
HTML7007: One or more blob URLs were revoked by closing the blob for
which they were created. These URLs will no longer resolve as the data
backing the URL has been freed.
What does it mean and how can I fix it?
Try this using, this or useragent
if (navigator.appVersion.toString().indexOf('.NET') > 0)
window.navigator.msSaveBlob(blob, filename);
else
{
var blob = new Blob(['stringhere'], { type: 'text/csv;charset=utf-8' });
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = URL.createObjectURL(blob);
link.download = 'teams.csv';
link.click();
}
IE won't allow you to open blobs directly. You have to use msSaveOrOpenBlob. There's also msSaveBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
I needed to use a Blob to download a converted a base64 PNG image. I was able to successfully download the blob on IE11 with window.navigator.msSaveBlob
See the following msdn link:
http://msdn.microsoft.com/en-us/library/hh779016(v=vs.85).aspx
Specifically, you should call:
window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');
where blobObject is a Blob created in the usual fashion.
Complete Solution for Chrome, Internet Explorer Firefox and Opera
There are lots of nice bits on this page, but I had to use a combination of a few things to get it all to work. Hopefully this helps you.
Use a button or link to trigger a function called download():
<button class="button-no save-btn" ng-click="download()">DOWNLOAD</button>
Put this in your controller:
$scope.download = function () {
// example shows a JSON file
var content = JSON.stringify($scope.stuffToPutInFile, null, " ");
var blob = new Blob([content], {type: 'application/json;charset=utf-8'});
if (window.navigator && window.navigator.msSaveBlob) {
// Internet Explorer workaround
$log.warn("Triggering download using msSaveBlob");
window.navigator.msSaveBlob(blob, "export.json");
} else {
// other browsers
$log.warn("Triggering download using webkit");
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create invisible element
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', url);
downloadLink.attr('download', 'export.json');
// make link invisible and add to the DOM (Firefox)
downloadLink.attr('style','display:none');
angular.element(document.body).append(downloadLink);
// trigger click
downloadLink[0].click();
}
};
What's your IE browser version? You need a modern browser or IE10+
http://caniuse.com/bloburls
Maybe you need some delay. What about with:
link.click();
setTimeout(function(){
document.body.createElementNS('http://www.w3.org/1999/xhtml', 'a');
URL.revokeObjectURL(link.href);
}, 100);
I needed to get the download feature to work in Chrome and IE11. I had good success with this code.
HTML
<div ng-repeat="attachment in attachments">
<a ng-click="openAttachment(attachment)" ng-href="{{attachment.fileRef}}">{{attachment.filename}}</a>
</div>
JS
$scope.openAttachment = function (attachment) {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(
b64toBlob(attachment.attachment, attachment.mimeType),
attachment.filename
);
}
};
Done it this way, working fine for me.
downloadFile(data) {
if (navigator.msSaveBlob) {
let blob = new Blob([data], {
"type": "text/csv;charset=utf8;"
});
navigator.msSaveBlob(blob, this.fileName);
}
else {
let blob = new Blob(['\ufeff' + data], { type: 'text/csv;charset=utf-8;' });
let $link = document.createElement("a");
let url = URL.createObjectURL(blob);
$link.setAttribute("target", "_blank");
$link.setAttribute("href", url);
$link.setAttribute("download", this.fileName);
$link.style.visibility = "hidden";
document.body.appendChild($link);
$link.click();
document.body.removeChild($link);
}
}
Try to use this instead :
var blob = file.slice(0, file.size);
Create polyfill method as below,had a variable filename since in my case download filename was static.This method will be called while blob function is not supported as in case of Internet explorer
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype,
'toBlob', {
value: function (callback, type, quality) {
var canvas = this;
setTimeout(function () {
var binStr = atob(canvas.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
var blob = new Blob([arr], {
type: 'image/png'
});
window.navigator.msSaveOrOpenBlob(blob, fileName);
});
}
});
}
try {
const blob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
const file = new File([blob], this.getFileName(res), {
type: res.headers.get('Content-Type'),
});
saveAs(file);
} catch (err) {
var textFileAsBlob = new Blob([res.body], {
type: res.headers.get('Content-Type'),
});
window.navigator.msSaveBlob(textFileAsBlob, this.getFileName(res));
}
To get the file name. Use the below function.
getFileName(response: any) {
let name: string;
try {
const contentDisposition: string = response.headers.get(
'content-disposition'
);
const [, filename] = contentDisposition.split('filename=');
name = filename;
} catch (e) {
name = 'File_Name_Not_Specified_' + new Date();
}
return name;
}
This worked for me.

Categories