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>
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>
I want to download an image in JS which is base64 encoded. For this, I have first decoded the image and tried to download it. The file is downloading but the content in the downloaded files are nothing.
The encoded image is like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
I used the following code to decode and download the image:
var imgdata = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
var imggetbase64decode = imgData.replace(/^data:image\/(png|jpg);base64,/, ""); // imgData is the encoded base64 string.
var data = imggetbase64decode, fileName = "my-download.png";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var json = data,
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
I got the error during opening the downloaded file is:
Could not load image 'my-download.png'.
Here you can get what you are looking for
How to download a base64-encoded image?
if not please share some codepen link so i can help you out.
I allow the user to select a mp3 file from the local file System and then
allow to download the same file. Its for learning purpose.
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
var fReader = new FileReader();
fReader.onload = function(ev) { //onload event
var dataUrl = ev.target.result;
var downloadCon = document.querySelector('#download')
downloadCon.href = dataUrl;
};
fReader.readAsDataURL(file); //start reading the file
}
});
}
</script>
The HTML body:
<body>
<div class="controls">
<input type="file" id="musicFile">
<a id='download'href='#' download='music.mp3' class='downloadLink'>
Download File
</a>
</div>
</body>
When I click the Download File, nothing happens. Can you tell me what am I doing wrong?
You don't need to use FileReader to do that. Simply, you need to create a URLObject and make the A tag to point to it. The code for that (tested under Chrome and Firefox for Linux):
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
document.getElementById( 'download' ).href = URL.createObjectURL(file);
}
});
}
</script>
To be more specific at what I did in your code - I removed all the FileReader code and added
document.getElementById( 'download' ).href = URL.createObjectURL(file);
in it's place. I didn't touch your HTML.
Hope that helps.
I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
If you want to download it using JavaScript (without any back-end) use:
window.location.href = 'data:application/octet-stream;base64,' + img;
where img is your base64 encoded image.
If you want to allow the user to specify a file name, use the download attribute of the a tag:
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
Notice: The download attribute is not supported by very old browsers
Simple way to do this with Javascript...
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
It is so simple just use function below:
// Parameters:
// contentType: The content type of your file.
// its like application/pdf or application/msword or image/jpeg or
// image/png and so on
// base64Data: Its your actual base64 data
// fileName: Its the file name of the file which will be downloaded.
function downloadBase64File(contentType, base64Data, fileName) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
I found this solution from the sourcecode of how Chrome takes full-page screenshots.
const base64string = "";
const pageImage = new Image();
pageImage.src = 'data:image/png;base64,' + base64string;
pageImage.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = pageImage.naturalWidth;
canvas.height= pageImage.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImage(pageImage, 0, 0);
console.log(canvas, pageImage)
saveScreenshot(canvas);
}
function saveScreenshot(canvas) {
let fileName = "image"
const link = document.createElement('a');
link.download = fileName + '.png';
console.log(canvas)
canvas.toBlob(function(blob) {
console.log(blob)
link.href = URL.createObjectURL(blob);
link.click();
});
};
I don't know whether am late to answer this, but I think the better solution could be this.
Create a file from the base64string
const convertBase64ToFile = (base64String, fileName) => {
let arr = base64String.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let uint8Array = new Uint8Array(n);
while (n--) {
uint8Array[n] = bstr.charCodeAt(n);
}
let file = new File([uint8Array], fileName, { type: mime });
return file;
}
Install File Saver from npm with
npm install file-saver
Import File Saver
const { saveAs } = require('file-saver');
/// OR
import { saveAs } from 'file-saver';
Using File Saver download the file
const downloadBase64Data = (base64String, fileName) => {
let file = convertBase64ToFile(base64String, fileName);
saveAs(file, fileName);
}
If this Answer has worked for you please upvote it and mark it as correct to help others easily find it
You can try this :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Download Text File DataURL Demo</title>
<style>
body{ font: menu; }
</style>
<script src='//js.zapjs.com/js/download.js'></script>
</head>
<body>
<h1>Download Text File DataURL Demo</h1>
<main></main>
<script>
download("data:application/octet-stream;base64,YOUR BASE64URL", "dlDataUrlText.jpeg", "application/octet-stream;base64");
</script>
</body>
</html>
download tag downloads the image using the script included.
For reference you can try this URL : http://danml.com/download.html
In my Angular App, I am getting the base 64 files from server.
In Html:-
<button type="button" (click)="downloadFile(fileName,base64data,fileType)"></button>
In Ts:-
downloadFile(fileName:string,data: any,fileFormat:string): void {
const linkSource = 'data:'+fileFormat+';base64'+data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
If you already have it in base64, add the image tag in front of the base64. attach it to the element
png64 = "data:image/" + png64;
$('#downloadPNG').attr('href', png64);
Add the file name that you want when downloading to the download tag.
<a download="chart.png" id="downloadPNG">Export img</a>
In my React App, I was getting the base 64 images from an API, I stored it in a global prop and downloaded it with the help of <a> tag.
<a href={`data:application/octet-stream;base64,${this.props.base64image}`} download={"imageName"}>Click to Download the image</a>
At first: This question is extremly browser dependent! I tried many, so I came up to answer this question that way:
You should put the base64-Data inside the src-Tag of an IMG-Element:
How to display Base64 images in HTML?
Then you can right click the Image and click "Save Image..." (or similar) in these browsers:
Chrome 79
Edge 44
Firefox 71
IE 11
Safari 13
Also on Android with Chrome and Firefox.
Biggest file working was 23 MB PNG-File in IE 11 and Safari 13. But Firefox and Chrome did also work for 86 MB JPEG.