How to download newly created HTML file? - javascript

I create an HTML file with document.implementation.createHTMLDocument() function. Like so:
var doc = document.implementation.createHTMLDocument("My New Document");
And I want to download this newly create HTML document. I tried this:
var link = document.createElement('a');
link.href = doc;
link.download = 'newDoc.html';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
But doesn't work. It redirects me to myDomain.com/[object HTMLDocument]. How can I download this file?

A Couple of stages.
Place the HTML of the document into a blob,.
Convert blob into a blob url
Create a link to download this url
Example below..
const bt = document.querySelector('button');
bt.addEventListener('click', () => {
//lets create some document
const doc = document.implementation.createHTMLDocument("My New Document");
const hello = doc.createElement('p');
hello.innerText = 'Hello';
doc.body.appendChild(hello);
//now get it's contents and place into a blob
const blob = new Blob([doc.documentElement.innerHTML], {
type: 'text/html'
});
//now convert to url
const docUrl = window.URL.createObjectURL(blob);
//were done, lets create a href to this and download
const aclick = document.createElement('a');
aclick.href = docUrl;
aclick.download = 'download.html';
aclick.click();
//tidy up
window.URL.revokeObjectURL(docUrl);
});
<p>Click button below to download some HTML</p>
<button>download</button>

You cannot append the filename in URL, Because the HTML File that you created using createHTMLDocument() is not a actual HTML file and Not available in your server, It's a Javascript HTMLDocument Object.
You can use Data URI, as follows, Complete Tutorial Here..
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download("newDoc.html","<html><head><title>Hello</title></head><body>Hello World!</body></html>");
NOTE: The function encodeURIComponent() will not affect the HTML after download.

function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
function myFunction(){
let html = document.getElementById("textarea").value;;
download("hello.html", html);
}
<textarea id="textarea" placeholder="Type your HTML here..."><h1>WORKING?????</h1></textarea>
<button onclick="myFunction()">GET FILE</button>

Related

Download File through JavaScript

I have created a function to download the file, but the issue is it opens the file on the same tab, I a trying to force download this file in the system.
I read other threads but didn't get the answer as I was expected and helpful.
Please help me create this function that downloads the file.
I have tried this code as below
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.click();
link.remove();
}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
Seems like - as with normal links - you need to set the target attribute.
Note: snippet won't work here because popups are blocked. This means that it does work.
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.setAttribute("target", "_blank");
link.click();
link.remove();
}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');
here is a typical js download function sample. In your code, firstly you should replace 'name' with name, using the variable given.
function loadPdfFile(uri, pFileName) {
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = pFileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
The reason why it only opens the PDF might be you are running your code locally, you could try to put it to your server and test.
If you want to open the file in a new tab, you can simply add a target="_blank" attribute (link.setAttribute("target", "_blank");).
If you want to forcefully download the file instead of opening/previewing it in the browser, you can convert the file URI to a blob. For example:
async function downloadURI(uri, name) {
const link = document.createElement("a");
link.download = name;
const data = await fetch(uri).then((res) => res.blob())
link.href = window.URL.createObjectURL(
new Blob([data], { type: 'application/pdf' })
);
link.click();
link.remove();
window.URL.revokeObjectURL(link.href);
}
JS Fiddle: https://jsfiddle.net/sh4dfm6a/
if you need to open it in new tab just add target attribute like below EX
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = 'name';
link.href = uri;
link.target = "_blank";
link.click();
link.remove();}
downloadURI('https://example.com/myfile.pdf', 'customefilename.pdf');

How do I create a text file using pure JavaScript, then append to it?

I want to append data into a txt file. I looked at other questions, and all of the answers were only supported in IE. This is what I have so far (I'm a complete JavaScript rookie, so I don't know anything about doing this kind of stuff):
var word = "word";
//Missing Code
What is the pure JavaScript code here????
I found old answer here
const createTextFile = (fileNmae, text) => {
const element = document.createElement('a');
element.setAttribute(
'href',
'data:text/plain;charset=utf-8,' + encodeURIComponent(text),
);
element.setAttribute('download', fileNmae);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
};
createTextFile('test.txt', 'word');
let data = "some"
let file = new Blob([data], {type: "txt"})
// Appending to the file can be mimiced this way
data = data+"Text"
file = new Blob([data], {type: "txt"})
// To Download this file
let a = document.createElement("a"), url = URL.createObjectURL(file);
a.href = url;
a.download = file;
document.body.appendChild(a);
a.click()
setTimeout(function() {
document.body.removeChild(a);
}, 0);
Hope this can help

Download a File from a URL and save it on local folder, the link of it is as shown below in the question body

http://Company site/download_file?file_name=28528082-002-SH01.TIF&file_handle_name=MTIObjectHandle-0002-1~R~DghrOwfkoktsvsuGKP1--Pg7~p4Tiff~DELPHIDB~~
And the form selecting inspect element
28528082-002-SH01.TIF
I am not a Java programmer and I'm trying some of the codes from the internet but none of them work as I needed.
<button id="download" onclick="downloadFile()">download file</button>
<script>
document.getElementById('download').onclick = async function downloadFile(){
let s = await fetch(URL_OF_THE_FILE);
let link = document.createElement('a');
const blob = new Blob([await s.arrayBuffer()], { type: s.type });
link.href = window.URL.createObjectURL(blob);
link.download = NAME_OF_THE_FILE;
link.click();
}
</script>

Making a downloadable file with the dataURL

I am trying to make a downloadable file from only a dataURL and I am not sure why it is not working. I am reading the dataURL from a file and inserting its dataURL into an with the download attribute. but when i generate de click the page goes blank and says it canĀ“t find the page. Here is how I am trying to do it.
reader.readAsDataURL(file);
reader.onload = function (evt) {
var element = document.createElement('a');
element.setAttribute('href', evt.target.result);
var name=filename.split(".");
element.setAttribute('download', 'filename');
element.style.display = 'inline-block';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
From the code above I obtain this
How can I properly make a download action for the dataURL?
Your approach is wrong.
The readAsDataURL method is used to read the contents of the specified Blob or File.
The result will be base64 encoded string.
The readAsDataUrl method can be used to make a image preview.
To download the file you can go by this approach
<!DOCTYPE html>
<html>
<head> </head>
<body>
<form>
<label for="file">ChooseFile</label>
<input type="file" id="myFile" accept="image/*">
</form>
<script>
document.getElementById("myFile").addEventListener("change", downloadFile);
function downloadFile() {
let file = this.files[0];
let url = URL.createObjectURL(file);
let link = document.createElement('a');
link.href = url;
link.download = file.name;
link.click();
link = null;
URL.revokeObjectURL(url);
}
</script>
</body>
</html>
Useful resources
FileReader
createObjectURL
revokeObjectURL

How can I make my file download work on IE and safari?

I'm trying to create and download a file on client side with the following code:
function downloadFile(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.click();
}
Although this only works on chrome. Nothing happens on safari and IE. How can I make it work?
Not sure if youve figured this out or not but for this to work in safari you need to create an event and dispatch on the created element like this:
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'data:application/octet;charset=utf-8,' + encodeURIComponent(data));
downloadLink.setAttribute('download', fileName);
downloadLink.style.display = "none";
downloadLink.onclick = function (event) {
document.body.removeChild(event.target);
};
var clk = document.createEvent("MouseEvent");
clk.initEvent("click", true, true);
downloadLink.dispatchEvent(clk);
document.body.appendChild(downloadLink);
downloadLink.dispatchEvent(clk);`
I used this to save my file in CSV/excel format and works in chrome/IE/Safari
refer and make changes needed
var fileName = name + "["+ name1 +"]";
var uri = 'data:text/csv;charset=utf-8,' + escape(finalResult);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
location.reload();

Categories