Create file and download on button click with JavaScript - javascript

I am trying to write a function which will get the value from textarea and download it as an HTML file.
The HTML file
<textarea id="text-val" rows="4"></textarea>
Download your Code
The Javascript Function
function download(filename, html) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "MyCode.html";
download(filename, html);
}, false);
My question is : If a user put some external code source in textarea, as an example some image link. How can I download that image too and create a folder like images and put that image inside folder.
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.
document.getElementById("dwn-btn").addEventListener("click", function(){
// Generate download of hello.txt file with some content
var text = document.getElementById("text-val").value;
var filename = "hello.html";
download(filename, text);
}, false);
<textarea id="text-val" rows="4"></textarea>
Download your Code

You can't download folders inside a browser. Although you might create a zip, either client side or server side, and download that zip

I know this code isn't optimized and a bit hacky but you can use it as a starting point.
It converts the image URL into base64 so it can be used inline with the downloaded HTML file.
document.getElementById("dwn-btn").addEventListener('click', function(event) {
event.preventDefault();
var content = document.getElementById("text-val").value;
content.match(/(src=".+"|src='.+')/g).forEach(function(match) {
var imageURL = match.substring(5).slice(0, -1);
var imageElem = document.createElement("img");
toDataURL(imageURL, function(dataUrl) {
var regex = new RegExp(imageURL);
content = content.replace(regex, dataUrl);
});
});
setTimeout(function(){
var blob = new Blob([content], {type: "text/html"});
var link = document.createElement("a");
link.download = "mydownloadedcode.html";
link.href = window.URL.createObjectURL(blob);
link.dispatchEvent(new MouseEvent("click"));
}, 2000);
});
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
<textarea id="text-val" rows="4">
<img id="imageid" src="https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0">
<img id="imageid" src='https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0'>
</textarea>
Download your Code

Try this URL, might be your issue solved
https://viralpatel.net/blogs/create-zip-file-javascript/
https://davidwalsh.name/javascript-zip

Related

Js/Jquery how to remove previous image thumbnail when choose another image?

I'm doing an upload function that will allow the user to upload a chosen image to the server, and it is supposed to show a thumbnail of the current image. But when another image is chosen, it will add in the newer image thumbnail, and wouldn't remove the older image thumbnail.
So, how do I remove the previous image thumbnail and replace it with the newer one?
Here is my javascript code:
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 200;
image.title = file.name;
image.style.marginTop = '10px';
image.style.marginRight = '10px';
image.style.borderRadius = '3px';
image.style.marginBottom = '220px';
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
And here is my HTML code:
<input type="file" id="browse" accept='.jpeg, .png, .jpg' onchange='previewFiles()' name="image" />
<div id='preview'></div>
Thanks in advance!
You need to remove all the children before adding new one.
reader.addEventListener("load", function () {
var image = new Image();
image.height = 200;
image.title = file.name;
image.style.marginTop = '10px';
image.style.marginRight = '10px';
image.style.borderRadius = '3px';
image.style.marginBottom = '220px';
image.src = this.result;
//removes all children (images)
preview.childNodes.forEach(c => preview.removeChild(c));
preview.appendChild(image);

How to download a GIF from a given URL using Javascript

I am trying to download a GIF from Giphy (just need to download it, I don't need to display it on the browser).
I tried using the solution in this question this question however it downloads a static image:
function download_img(e, link){
var image = new Image();
image.crossOrigin = "anonymous";
image.src = link;
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this, 0, 0);
var blob;
// ... get as Data URI
if (image.src.indexOf(".jpg") > -1) {
blob = canvas.toDataURL("image/jpeg");
} else if (image.src.indexOf(".png") > -1) {
blob = canvas.toDataURL("image/png");
} else if (image.src.indexOf(".gif") > -1) {
blob = canvas.toDataURL("image/gif");
} else {
blob = canvas.toDataURL("image/png");
}
tempbtn = document.createElement('a');
tempbtn.href = blob;
tempbtn.download = 'giphy.gif'; // or define your own name.
tempbtn.click();
tempbtn.remove();
};
}
<a href="#" onclick="download_img(this,'https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif')" > Descargar gif </a>
I also wonder why it's needed to create a new Image(); and create a canvas tag
This works for me, I took some of the code from here
https://randomtutes.com/2019/08/02/download-blob-as-file-in-javascript/
(async () => {
//create new a element
let a = document.createElement('a');
// get image as blob
let response = await fetch('https://media2.giphy.com/media/DvyLQztQwmyAM/giphy.gif?cid=e9ff928175irq2ybzjyiuicjuxk21vv4jyyn0ut5o0d7co50&rid=giphy.gif');
let file = await response.blob();
// use download attribute https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
a.download = 'myGif';
a.href = window.URL.createObjectURL(file);
//store download url in javascript https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access
a.dataset.downloadurl = ['application/octet-stream', a.download, a.href].join(':');
//click on element to start download
a.click();
})();
I managed to get this working in Chrome and Firefox too by appending a link to the to document.
var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

How to create an Image file from dataURL and save it?

I have found a way to save it as PDF but now I need to save it as Image.
This is my code:
function downloadCert()
{
html2canvas($('#canvas'), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/jpeg");
console.log(imgData);
var pdf = new jsPDF();
pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);
pdf.save("download.pdf");
}
});
}
const downloadFile = () => {
const imgUri = 'data:image/gif;base64,R0lGODlhPQBEA....' //Image base64 uri
const link = document.createElement('a')
document.body.appendChild(link)
link.href = imgUri
link.target = '_self'
link.fileName = 'test_file_download.gif'
link.download = true
link.click()
}
The format in base64 string and the file extension should match for file to open properly. In above case, it's gif
Use this:
function blobCallback(fileName) {
return function(b) {
var a = document.createElement('a');
a.download = fileName+ '.jpeg';
a.href = window.URL.createObjectURL(b);
a.click();
}
}
$('#canvas').toBlob(blobCallback('DownloadFileName'), 'image/jpeg');

Download canvas as image not working in firefox and microsoft edge

I want to download canvas as image but not working in firefox and microsoft edge but working with chrome
This is my code :
DownloadImage = (i) => {
var _this = this;
this.modeler.saveSVG(function (err, svg) {
if (err) console.log(err)
_this.setState({ datasvg: svg }, function () {
const canvas = _this.refs.canvasforimage;
const options = {
log: false,
ignoreMouse: true,
};
canvg(canvas, this.state.datasvg, options);
const image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
const element = document.createElement("a");
element.setAttribute('download', 'diagram.png');
element.setAttribute('href', image);
element.click();
are there any solution ?
This is the code I use to save canvas contents as PNG image file:
canvas.toBlob(blob => {
var a = document.createElement("a"),
url = URL.createObjectURL(blob);
a.href = url;
a.download = "image.png";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
});

Why does this .toBlob() method of downloading a canvas require two clicks to work?

I would like to make an image on a canvas element ("canvas") downloadable.
I can't use right click > save as, as the actual canvas used is hidden. The user will only see a smaller representation of the full-size image on a separate canvas.
I was able to make this work using .toDataURL, but this failed when images/canvases became of a certain size. I am trying to combat this with .toBlob().
I have been able to get the below to work, but it initially takes two clicks to fire, and requires two clicks again every time the image is changed.
Download Canvas as PNG
var link = document.getElementById("download");
link.onclick = function() {
link.download = "image.png";
canvas.toBlob(function(blob){
link.href = URL.createObjectURL(blob);
},'image/png');
}
How can I eliminate the need to click twice each time I change the canvas image?
.toBlob() is asynchronous (hence the function as parameter).
You have to wait until the function has finished its work before you can trigger the download.
var link = document.getElementById("download");
link.onclick = function() {
document.querySelector("canvas").toBlob(function(blob){
// here the conversion has finished
// to trigger the download (again) we use a dummy link
var a = document.createElement("a");
a.download = "image.png";
a.href = URL.createObjectURL(blob);
a.click();
},'image/png');
};
Example
var link = document.getElementById("download");
link.onclick = function() {
document.querySelector("canvas").toBlob(function(blob) {
var a = document.createElement("a");
a.download = "image.png";
a.href = URL.createObjectURL(blob);
a.click();
}, 'image/png');
};
var change = document.getElementById("change");
change.onclick = function() {
var c = document.querySelector("canvas"),
ctx = c.getContext("2d");
ctx.fillStyle = getRandomColor();
ctx.fillRect(0, 0, c.width, c.height);
};
change.onclick();
function getRandomColor() {
return "rgb(" + (~~(Math.random() * 256)) + "," + (~~(Math.random() * 256)) + "," + (~~(Math.random() * 256)) + ")";
}
Download Change canvas
<br />
<canvas width="2000" height="2000"></canvas>

Categories