How to specify the download file name in FrontEnd - javascript

UPDATE:
Creating a Blob from a base64 string in JavaScript
I am trying to implement click a button and download file from its DataURL.
Currently, since the Chrome has restricted the old way such as building <a> link which throws error like:
Not allowed to navigate top frame to data URL: ....
The solution I found is open new window with iframe and set the DataURL as its src
let jpgWindow = window.open("", "_blank")
var html = "<html><body><iframe width='100%' height='100%' src='data:application/jpeg;base64, "+ theDataURL+"'></iframe></body></html>";
jpgWindow.document.write(html)
When I click the button, the download works, but the picture is downloaded with filename "download", there is no way I can specify what file name I want it default to.
Any thought?

Look into window.URL.createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
const blob = new Blob(['array of data in your file'], {type : 'text/rtf'});
const anchor = document.createElement('a');
anchor.href = window.URL.createObjectURL(blob);
anchor.download = 'the-file-name.txt';
anchor.click();

Related

How to display pdf using base64 pdf string in Angular 8?

I'm using angular 8 to get the base64 pdf string with iframe to open in new tab but its not opening in internet explorer showing blank page in IE. So i do not want to use iframe to open pdf. Can anybody help me to display base64 pdf string in IE.
Salam mate,
you should first convert the Base64 to blob, you can do it as it shows in this question:
Creating a BLOB from a Base64 string in JavaScript
Then you should use [window.URL.createObjectURL(fileblob)] to convert your blob into URL, after that just create anchor and click it, like follows:
var fileblob = b64toBlob('<your_base64>', 'application/pdf');
var url = window.URL.createObjectURL(fileblob);
let anchor = document.createElement("a");
anchor.href = url;
anchor.target = "_blank"
anchor.click();

base64 string to pdf download

I am facing issue to download pdf in SAPUI5 application. Issue is Getting base64 string from backend system but not able to convert it and display as PDF.
I am able to convert the base64 and download also but only small size.
Not able to download for larger PDF file its downloading but shows download failed.
kindly help me out
var data =" JVBERi0xLjQNJeLjz9MNCjc1MDEgMCBvYmogPDwvTGluZWFyaXplZCAxL0wgOTM2NDM1Mi9PIDc1MDMvRSAxMjE3ODgvTiA1MjIvVCA5MjE0MjgzL0ggWyA2..";
var uri = 'data:application/pdf;base64,' + atob(data);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = object.FileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Saving the data as a blob and setting the download link to get the data from the blog may solve your problem for large files. The most effective way in this mechanism is to get the data from your server as binary instead of Base64. It works with base64 too - but it is just a resource over kill in the blob scenario.
var data = Uint8Array.from(atob(base64_string), c => c.charCodeAt(0));
var blob = new Blob([data], {type: "octet/stream"});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
...
...
As per you current solution, a hyperlink will be created with href contains data:application/pdf;base64,' + base64Data. When the hyperlink is clicked the complete URL will be opened in the browser new tab, which makes the browser to download the PFD file.
If the base64 data is bulk then the browser will take time to download PDF. Sometimes browser will be crashed OR leads to download failed error as it takes too much of time to download.
Alternative Options
Using GET_STEAM method you can download the pdf from the backend only.
Using download plugins like downloadjs, FileSaver.js, StreamSaver.js.
As per you requirement you can get different available plugins for file downloading using client-side JavaScript
Here is a sap blog entry solving your problem.
TLDR:
var base64EncodedPDF = "JVBERi0xLjcNCiW..."; // the encoded string
var decodedPdfContent = atob(base64EncodedPDF);
var byteArray = new Uint8Array(decodedPdfContent.length)
for(var i=0; i<decodedPdfContent.length; i++){
byteArray[i] = decodedPdfContent.charCodeAt(i);
}
var blob = new Blob([byteArray.buffer], { type: 'application/pdf' });
var _pdfurl = URL.createObjectURL(blob);
this._PDFViewer.setSource(_pdfurl);

Angular - Save blob in local text file?

I have a plain text variable which I want to store and save on a .txt file using Angular.
So far I have tried the following:
var data = new Blob([text], {type: 'text/plain'});
const url= window.URL.createObjectURL(data);
window.open(url);
Being text the variable with the plain text content. It seems to work but it opens de blob on a new browser tab, and I need it to be downloaded as whatever.txt.
How can I achieve this? Thanks!
The solution can be found here:
JavaScript blob filename without link
The steps are the following:
Create a hidden <a> tag.
Set its href attribute to the blob's URL.
Set its download attribute to the filename.
Click on the <a> tag.
This is working code from my application
const file = new window.Blob([data], { type: contentType });
const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";
const fileURL = URL.createObjectURL(file);
downloadAncher.href = fileURL;
downloadAncher.download = fileName;
downloadAncher.click();

How to link to data URL without Firefox adding "unsafe" prefix

I'm trying to create a download link in an angular app that makes data in a model downloadable as a CSV file. I have it all working except for the actual download link. Using filesaver.js is blowing up unit tests in Karma so I'm exploring just doing it manually.
Below is what I have. In the controller:
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
$scope.downloadUrl = URL.createObjectURL(blob);
In the view, I have:
<a ng-href="{{downloadUrl}}" download="ttester.csv" id="download">Download</a>
The issue is this opens a new page in Firefox 20 with the URL "unsafe:blob:af775c64-dcb1-864a-8eaa-adebe7f101a7", notice the "unsafe:" prefix. Removing that prefix downloads the data correctly, but without the filename I want.
What am I missing in my hyperlink to make it work? I expect it to open a download dialog with the filename tester.csv for the file.
Really appreciate any help
You could use the following code that will create the blob, a fake link and will dispatch a click event on this fake link. Note that no new page should be opened but you will be directly prompted with the save dialog box.
var blob = new Blob([data.join('\n')], {type: 'text/csv;charset=utf-8'});
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = 'teams.csv'; // whatever file name you want :)
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
link.dispatchEvent(event);
You can see a working Fiddle here

How can I have "Export as CSV" button in Chrome Extension?

I created a Chrome extension which scans the page and creates a list of h1-h6 tags of a current page in a popup window. This is how this list looks like for main StackOverflow page:
h1 | All Questions
h3 | XmlElement has a list as attribute but its items aren't separated by comma
h3 | Eclipse, Easily remove/fix all #Override due to Java version change
...
I'd like to have an "Export" button, which would give me an ability to save this report in CSV format. Is it possible?
You can use data URI scheme to create a URI storing the CSV content. Then you can create a A element with a download attribute set to the desired file name.
If your CSV is really big, you should use BlobBuilder and webkitURL.createObjectURL instead of data URI scheme to create the link href.
Here is an example using data URI scheme:
var link = document.createElement("a");
link.textContent = "Save as CSV";
link.download = "file.csv";
link.href = "data:text/csv,h1;All Questions\n"
document.body.appendChild(link);
When the user will click the link, the "file.csv" will be automatically saved in the default Download folder.
Based on #check_ca answer, I've coded the following to return a csv link element for array data:
function getCSVLinkElement(arr){
var link = document.createElement("a");
link.textContent = "Save as CSV";
link.download = "file.csv";
var csv = arr.map(function(v){return v.join(',')}).join('\n');
link.href = encodeURI("data:text/csv,"+csv);
return link;
}
var el = getCSVLinkElement([['num','sq'],[2,4],[3,9]]);
document.body.appendChild(el);

Categories