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();
Related
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);
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();
I am having some text like below to be saved in a downloadable doc format using javascript blob.
<p style='font-size:18px'>Hello</p>
Once the download happens I want the doc to show just show formatted 'Hello' without any html tags. In ubuntu this works very well.
But when I open the same doc in windows or google docs, I still see html tags.
Is there a way where I can do this formatting at Blob level itself. Below is the way Iam creating blob object.
var file = new Blob([val], {type: "octet/stream"});
Appreciate your help on this.
Try adjusting type of Blob to "text/html" , using URL.objectCreateURL() as file object reference for download
var val = "<div>abc</div>";
var file = new Blob([val], {
type: "text/html"
});
// file object reference
var download = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = download;
a.download = "file-" + new Date().getTime();
document.body.appendChild(a);
a.click()
During implementation of file transfer use case through WebRTC protocol, i am recieving data from queue at reciever end in some variables but unable to use that. Through some digging, i came to know that it can be done using Blob,
code snippet that i used :
var data=reciever.dequeue();
if(data)
{ var blob = new Blob(_base64ToArrayBuffer(data), {type: 'text/plain'});
// need to know how to proceed now?
}
file is need to be saved in local system.Thanks in advance.
You can create a temp anchor element element and append it to document.body, trigger click event. Done.
Here is the demo code:
var url = objectURL = URL.createObjectURL(blob); //your blob object here
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "YourFileName";
anchor.click(); //This will trigger browser download event.
Here is document about blob to URL.
Here is the blob document.
Hope this works. : )
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