I am trying to create a button that triggers a download of a JSON file. (And please i don't want to use any libraries to achieve this). Thank you.
import Data from '../Data';
let data = Data;
<Button>Download</Button>
Triggering browser download from front-end is not reliable.
What you should do is, create an endpoint that when called, will provide the correct response headers, thus triggering the browser download.
Front-end code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser.
Take a look at this solution: How to create a file in memory for user to download, but not through server? I have rewritten their code a bit, but basically for your case, you'd want...
// Set globals
var mimetype = 'application/json';
var filename = 'yourfile.json';
// Create Dummy A Element
var a = window.document.createElement('a');
// createObjectURL for local data as a Blob type
a.href = window.URL.createObjectURL(new Blob([data], {
encoding: "UTF-8",
type: mimetype + ";charset=UTF-8",
}));
a.download = filename;
// Download file and remove dummy element
document.body.appendChild(a);
a.click();
a.remove();
You would need to create a file using your data and then create a downloadable link
and append it in whichever part of your application you would like to.
const fileName = "file";
const json = JSON.stringify(data);
const blob = new Blob([json],{type:'application/json'});
const href = await URL.createObjectURL(blob); // Create a downloadable link
const link = document.createElement('a');
link.href = href;
link.download = fileName + ".json";
document.body.appendChild(link); // This can any part of your website
link.click();
document.body.removeChild(link);
Related
The script file is rendered from server side, and when I using the code as below to download data from the script
const blob = new Blob([data]);
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "1.mp4";
a.click();
URL.revokeObjectURL(a.href);
it shows that document is not defined. Is there any way to solve this problem?
I solved the problem through split the code into two parts.
While server side rendering, I print the blob's url in console:
const blob = new Blob([data]);
console.log(URL.createObjectURL(blob));
And While client side rendering, I download the blob manually:
var a = document.createElement("a");
a.href = 'blob:{paste the url address}';
a.download = "1.mp4";
a.click();
URL.revokeObjectURL(a.href);
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);
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();
I have an app that converts files. I'm sending a file, and the converted file is being returned in the form of a data URL. Had everything working great in Chrome, but IE (10/11/Edge) is a different story. Have tried several things to no prevail:
1) HTML5 download attribute is not supported in IE. I tried assigning the returned URL as an anchor tag href, but invoking .click() is not supported, and manually clicking on the link does nothing.
2) window.navigator.msSaveOrOpenBlob() and File Saver.js. The SaveAs dialog pops up, but the blob is empty and never downloads anything.
var file= new Blob([returnedFile], {type: "application/pdf"});
window.navigator.msSaveOrOpenBlob(file, 'doc.pdf');
FileSaver.saveAs(file, 'doc.pdf');
Any ideas or suggestions to try?
First, try to verify saveAs existance:
if (window.saveAs) {
window.saveAs(blob, name);
} else {
navigator.saveBlob(blob, name);
}
As for the Blob itself:
create <a>
update href:
a.href = window.URL.createObjectURL(new Blob(returnedFile, {type: "application/pdf"}));
fire click event
More or less the same functionality can be reviewed there: http://jsfiddle.net/VB59f/2/
Ended up getting the browser via navigator.userAgent.match and handling the save based on each browser accordingly:
var saveData = (data, fileName) => {
IE:
FileSaver.saveAs(blob, fileName + "." + extension);
Chrome:
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.style.display = "none";
downloadLink.href = data;
downloadLink.download = fileName;
downloadLink.click();
I'm calling an api and returning a byte array, name, document type and mime type of a file and trying to add Javascript to download this file.
I've all the code wired in and it downloads a file but the file is empty. I'm using the following code:
result.success(function (data, status, headers, config) {
var arr = data.Document;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: data.MimeType}));
a.download = agreementId+data.DocType;
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
});
I've tried the same code without the conversion to Uint8Array but this just opens a document with the binary data in it, close but not quite there. Eg I get a download of a word document that contains:
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAATwAAAAAAAAAAEAAAUQAAAAEAAAD+////AAAAAE4AAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////spcEAJ2AJBAAA
ect