I am trying to export data to file.
The export works great for pretty much all files, but when I try to export large datasets it is not working.
any clues?
here is the code
a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
I used the following function. Not sure why it solved the problem. I guess it is a browser thing.
download(content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
} else if ('download' in a) { //html5 A[download]
var csvData = new Blob([content], { type: mimeType });
var csvUrl = URL.createObjectURL(csvData);
//a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.href = csvUrl;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
console.log(a);
//document.body.removeChild(a);
/*
setTimeout(function() {
a.click();
console.log(a);
document.body.removeChild(a);
}, 66);*/
return true;
} else { //do iframe dataURL download (old ch+FF):
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);
setTimeout(function() {
document.body.removeChild(f);
}, 333);
return true;
}
},
Related
i want to save chart html to word file as image
but word file can download but chart image is just X image it means doesn't have data
could you give me solution
function ExportToDoc(filename = "") {
html2canvas(document.getElementById("pyramid")).then((canvas) => {
canvas.toBlob((blob) => {
if (blob) {
myBlob = blob;
}
});
});
var HtmlHead =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var EndHtml = "</body></html>";
//complete html
// var html = HtmlHead + document.getElementById("pyramid").innerHTML + EndHtml;
var html =
HtmlHead +
"<img src='" +
URL.createObjectURL(
new Blob(new Uint8Array(myBlob), { type: "image/png" })
) +
"'/>" +
EndHtml;
// "<div id='export'><img class='hide' src='" + URLObj.createObjectURL() +"'/></div>"
//specify the type
var blob = new Blob(["\ufeff", html], {
type: "application/msword",
});
// Specify link url
var url =
"data:application/vnd.ms-word;charset=utf-8," + encodeURIComponent(html);
// Specify file name
filename = filename ? filename + ".doc" : "document.doc";
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
downloadLink.href = url;
downloadLink.download = filename;
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
enter image description here
for HTML
<Chart
id="pyramid"
...
</Chart>
chart is working well
function ExportToDoc(filename = "") {
var img = new Image();
html2canvas(document.getElementById("pyramid")).then((canvas) => {
img.src = canvas.toDataURL();
var HtmlHead =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var EndHtml = "</body></html>";
var html =
HtmlHead + "<img class='hide' src='" + img.src + "'/>" + EndHtml;
var blob = new Blob(["\ufeff", html], {
type: "application/msword",
});
var url =
"data:application/vnd.ms-word;charset=utf-8," +
encodeURIComponent(html);
filename = filename ? filename + ".doc" : "Document.doc";
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
downloadLink.href = url;
downloadLink.download = filename;
downloadLink.click();
}
document.body.removeChild(downloadLink);
});
}
I solved it by myself.
Also upgraded:
function htmlToFile(element, file = "hwp") {
var img = new Image();
html2canvas(document.getElementById("pyramid")).then((canvas) => {
img.src = canvas.toDataURL();
var header = "<html><head><meta charset='utf-8'></head><body>";
var footer = "</body></html>";
var sourceHTML =
header + "<img class='hide' src='" + img.src + "'/>" + footer;
var source =
"data:application/vnd.ms-word;charset=utf-8," +
encodeURIComponent(sourceHTML);
var fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = "Document." + file;
fileDownload.click();
document.body.removeChild(fileDownload);
});
}
I have to export my HTML table into Excel sheets. I researched a lot and found a solution. It works for me but the problem is, there is some image field in my table data and I want to remove it from table export (suppose the first column). How can I modify my code to get the desired result?
downloadVenues = () => {
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById("venue-table");
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
var filename = 'venues_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if (navigator.msSaveOrOpenBlob) {
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob(blob, filename);
} else {
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
Here is a way to remove all the td, tr, th or anything else with a class or id before exporting to Excel.
Set the class .remove-this to any th and td you want to remove.
function exportTableToExcel(tableID, filename = ''){
var table = document.getElementById(tableID);
var cloneTable = table.cloneNode(true);
jQuery(cloneTable).find('.remove-this').remove();
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = cloneTable;
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
Original code: https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/
I am trying to download the file saved in s3. So I have codes like below.
static public function download($key, $disk = 's3') : object
{
$file = FileHelper::get($key);
$local = Storage::disk('local');
$local->put(basename($key), $file);
$pathToFile = storage_path().'/app/'.basename($key);
$headers = [
'Content-Type' => \GuzzleHttp\Psr7\mimetype_from_filename(basename($key)),
'Content-Description' => 'File Transfer',
'Content-Disposition' => "attachment; filename=' ". basename($key),
'filename'=> basename($key)
];
$repsonse = response()->download($pathToFile, basename($key), $headers)->deleteFileAfterSend(true);
ob_end_clean();
return $repsonse;
}
And I have the javascript code like below.
downloadFile() {
var app = this;
var url = baseRoute + 'files/' + this.fileId + '/download';
axios.get(url, {
headers: {
Authorization: 'bearer ' + this.Authentication.tokenData().token,
responseType : "blob"
}
}).then(function (response) {
var today = ((new Date()).toISOString()).slice(2,10),
filename = today.replace(/-/gi, "")+' '+ app.fileTitle;
let blob = new Blob([response.data], {
type: response.headers['content-type']
});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}).catch(function (response) {
console.log(response);
});
}
The file is downloaded, however, the file is corrupted. (it would not open) I checked S3 bucket to see if the file is corrupted during upload, but it was fine there.
What am I doing wrong? Any advice or suggestion would be appreciated.
Thank you in advance.
Added: when I tried to view the image, it returned white squared which means its base64 encoded image. Does it have to do with being empty file?
I had to use standard XMLHttpRequest to work it like below.
downloadFile() {
var app = this;
var url = baseRoute + 'files/' + this.fileId + '/download';
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader('Authorization', 'bearer ' + this.Authentication.tokenData().token);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
if (this.status === 200) {
var today = ((new Date()).toISOString()).slice(2,10),
filename = today.replace(/-/gi, "")+' '+ app.fileTitle;
var blob = new Blob([xhr.response], {type: xhr.getResponseHeader('content-type')});
var objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
link.click();
window.URL.revokeObjectURL(blob);
}
};
xhr.send();
},
I have a function to download text file from server. It works on chrome but not work with IE 11.
Please help me.
Thanks and Regards.
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob ';
xhr.onload = function () {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
xhr.send();
xhr.onerror = function (e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
};
I am using angularjs and am trying to create a system of downloading a vcard created in javascript. In order for the vcard to work on mobile, the data needs to be downloaded through an a tag. The problem is everytime I set the href="data:text/vcard, "+ string it saves the vCard but removes the newlines. vCards only work with newlines
Is there any way to keep the newline characters while saving data?
$scope.saveVcard = function(){
var user = $scope.member;
var out_string = 'BEGIN:VCARD\nVERSION:2.1\n\rN:' + user.last_name + ';' + user.first_name + ';;;\n\r'; //name
out_string += 'FN:' + user.first_name + ' ' + user.last_name + '\n\r';//FN
if (user.phone){
out_string += 'TEL;CELL:' + user.phone + '\n\r';} //Phone
if (user.email){
out_string += 'EMAIL;PREF;INTERNET:' + user.email + '\n\r';}//Email
if (user.prof_pic){
out_string += 'PHOTO;PNG:'+user.prof_pic + '\n\r';}//picture
out_string += 'END:VCARD';
var a = document.createElement('a');
a.href = 'data:text/vcard,' + out_string;
a.target = '_blank';
a.download = 'contact.vcf';
console.log(a.href);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Aha, I figured it out, simply use the function encodeURIComponent().
var a = document.createElement('a');
a.href = 'data:text/vcard,' + encodeURIComponent(out_string);
a.target = '_blank';
a.download = 'contact.vcf';
console.log(a.href);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);