Download an image via button in javascript/html? - javascript

I've read through lots of questions here and tried a few things but none are working. What I want is for an image to be downloaded at the click of a button, but instead the image is opened in another tab briefly before closing again. Ideally I want to make the download automatic, but right now I want it just to work.
<script type="text/javascript">
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.innerHTML == "Image") {
//someFunction(element.href);
var name = element.nameProp;
var address = element.href;
saveImageAs1(element.nameProp, element.href);
return false; // Prevent default action and stop event propagation
}
else
return true;
};
var link = document.createElement('a');
link.href = 'https://cdn.glitch.global/ab1f9eaf-3be9-411b-9fa4-81a39033290e/1650333182176.png?v=1650469623980';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
function saveImageAs1(name, adress) {
if (confirm('CLICK')) {
window.win = open(adress);
setTimeout('win.document.execCommand("SaveAs")', 100);
setTimeout('win.close()', 500);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<p>
Image
</p>
</div>
</form>
</body>
^This is code I got from a question mixed with someone's solution to that question, but the image doesn't download.
<html>
<header></header>
<body>
<a id="download_image" href="" download="https://cdn.glitch.global/ab1f9eaf-3be9-411b-9fa4-81a39033290e/1650333182176.png?v=1650469623980">Download 1</a>
<a id="download_image" href="" download="https://cdn.glitch.global/ab1f9eaf-3be9-411b-9fa4-81a39033290e/1650333182176.png?v=1650469623980">Download 2</a>
</body>
</html>
this version is based from a different answer, it downloads something but the downloads can't be opened or viewed.
For background info I'm coding in glitch, which is an online coding site kinda like repl, on a chromebook. is it possible the problems are due to what I'm using?

You can try putting the image URL in href and download attribute like this?
<a id="download_image_1" href="https://cdn.glitch.global/ab1f9eaf-3be9-411b-9fa4-81a39033290e/1650333182176.png?v=1650469623980" download>Download 1</a>
<a id="download_image_2" href="https://cdn.glitch.global/ab1f9eaf-3be9-411b-9fa4-81a39033290e/1650333182176.png?v=1650469623980" download>Download 2</a>
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download
But be aware while download is supported by modern browsers, Chrome is now ignoring the download attribute for cross-origin content.
https://developer.chrome.com/blog/chrome-65-deprecations/#block-cross-origin-a-download

Related

how to make an auto download image in javascript by setTimeout?

<a id="download" href="link of your file">click here to download the file</a>.
<script>
var downloadTimeout = setTimeout (
function() {
window.location = document.getElementById('download').href;
}, 4000);
</script>
This is not what I want, I need the image will be automatically downloaded when
the time is stop by setTimeout but I can't get it. Please help me. Thank you
You can do it using HTML5. To download image, add download property to your link. Note that this doesn't work in some browsers. You can try it on JSFiddle.
Click here to download image
<canvas></canvas>
<script>
setTimeout(function(){
downloadCanvas();
}, 4E3);
function downloadImage(){
document.getElementById('download').click();
}
function downloadCanvas(){
var a = document.getElementById('download');
var b = a.href;
a.href = document.getElementsByTagName('canvas')[0].toDataURL();
downloadImage();
a.href = b;
}
</script>

Paperclip image set within script tags shows the image text url not the image - expandablebanners.js

I'm using expandablebanners.js on a rails site, the code I have to display the rollover image is;
<script type="text/javascript">
var roll_img = "<%= #advert.roll_img.url %>"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img);
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
the main image is displayed on the page as so;
<%= link_to image_tag(#advert.img(:horizontal) title: #advert.name,),
#advert.target_url, :id => 'squarecenterbottom' %>
when you rollover the main image it should show the rollover image but
when I rollover the image it just shows the rollover image's url (i.e as text), I don't know what the problem is....
the code output is;
<script type="text/javascript">
var roll_img = "http://localhost:3000/system/adverts/large_imgs/000/000/004/original/1n.jpg?1401967781"
var squarecenterbottom = ExpandableBanners.banner("squarecenterbottom", roll_img );
squarecenterbottom.animated = true;
squarecenterbottom.setDirection('down', 'center');
squarecenterbottom.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
<img alt="test22" height="90" src="/system/adverts/imgs/000/000/004/horizontal/2n.jpeg?1401818651" title="test22" width="730" />
</div>
and this is the code from the documentation that shows how it works;
<script type="text/javascript">
var squaretopleft = ExpandableBanners.banner("squaretopleft", "images/square_expanded.jpg");
squaretopleft.setCloseImage("images/closebutton.jpg", 'left', 'top');
squaretopleft.animated = true;
squaretopleft.setDirection('up', 'left');
squaretopleft.expandOnClick = false;
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded",function(){documentReady=true;});}
else if (!window.onload) window.onload = function(){documentReady=true;}
</script>
</head>
<body>
<a id="squaretopleft" href="www.yourwebsite.com"><img src="images/square.jpg" /></a>
</body>
</html>
This might be a path or HTML structure problem.
Things to check:
In your output, your <a> element comes right after <script>. Then there is a </div> closing tag. Do you have an opening <div> before all? Are they all in the <body>?
Since ExpandableBanners code sets up onload and DOMContentLoaded listeners, try moving that in the <head> of the document.
Your original image has .jpeg extension and roll image has .jpg. Nothing wrong with this but make sure you have the correct images (and extensions) in the right paths. e.g. original image is under /imgs folder and roll is under /large_imgs. Is this ok?
Try relative path for your roll image. In this case: remove http://localhost:3000 in the beginning. (Assuming your original image is showing ok.)
Few points:
Missing semicolon at the end of var roll_img... declaration
As Ruby Racer mentioned, the generated anchor tag is missing double quote <a href="www.example.com

why the following code doesn't perform as expected?

<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script>
function myFunction()
{
var img = document.getElementById("image");
if (img.src == "smiley.gif")
document.getElementById("image").src="landscape.jpg";
else
document.getElementById("image").src="smiley.gif";
}
</script>
<button type="button" onclick = "myFunction()"> click me </button>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>
I would like to let the HTML page to switch between two pictures each time user click the button, but the picture never changes.
When I change the
if (img.src == "smiley.gif")
into
if (img.src.match("smiley.gif"))
then the code works as expected.
Could anyone please let me know the reason?
devnull69 is right. If you set the img's source to a relative path, it's src attribute will still return the full URL. You need to either fully qualify the path to the image or strip the img.src value to just the final component (filename) and compare.
For example, you could do:
var imgFilename = img.src.substring(img.src.lastIndexOf("/") + 1);
if (imgFilename === "smiley.gif") {
// Do something.
}

jQuery Save Image Onclick

On my website I have a jQuery script that, if the download button is clicked it will open the image that you want in new window.
My question is, how can I make this script when you click the button the image will save automatically and not open in a new window.
My code :
<script type="text/javascript">
$(document).ready(function (){
$('#download-btn').click(function(){
var size = $('#size').val();
window.open(size);
});
})
</script>
First I try jqueryfiledonwloader but not work on image file,after a some searching I found below solution,This work for me charmly,try this
<script type="text/javascript">
$(document).ready(function (){
$('#download-btn').click(function(){
var link = document.createElement('a');
link.href = '/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'; // use realtive url
link.download = 'MyToy.jpeg';
document.body.appendChild(link);
link.click();
});
})
</script>
<button class="btn btn-success" style="width: 250px;" data-image="/media/result/online_resultjpg_Page68.jpg" data-exam="GMO" data-roll="110211" onclick="downloadCertificate(this);" >Download Certificate</button>
<script type="text/javascript">
function downloadCertificate(obj){
var link = document.createElement('a');
const image = $(obj).data("image");
const img_ext = image.split(".");
const ext = img_ext[img_ext.length - 1];
link.href = image;
link.download = $(obj).data("exam") + "_" + $(obj).data("roll") + ext;
document.body.appendChild(link);
link.click();
}
</script>
Yuseferi script solution could be transformed into a simple anchor tag we put before the closing of the #download-btn one:
<a href='/sites/default/files/toy/jpeg/image-1419683919_4851.jpeg'
download='MyToy.jpeg'>MyToy.jpeg</a>
By the way, download is a standard HTML5 anchor tag (MDN) attribute and, in script, it is flagged "experimental": maybe because of unwanted side effect. Still Yuseferi solution should be full proof.

How to save an image from canvas

Recently I've been attempting to create a photo booth by relying on Webrtc and have nearly completed all of the code except I've not been able to figure out a way to save the image after it has been captured.
This is the closest I've come so far to achieving my goal:
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>fotogoof</title>
<link rel="Stylesheet" href="css/bootstrap.css"/>
<link rel="Stylesheet" href="css/style.css"/>
<script type="text/javascript">
window.onload = function () {
var img = document.getElementById('screenshot');
var button = document.getElementById('saveImage');
img.src = '';
img.onload = function () {
button.removeAttribute('disabled');
};
button.onclick = function () {
window.location.href = img.src.replace('image/png', 'image/octet-stream');
};
};
</script>
</head>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<h2 class="brand">Html5 Photobooth</h1>
</div>
</div>
</div>
<div class="container" id="body-wrap">
<div class="container" id="main">
<div class="span10">
<div id="video-container">
<canvas width="400" height="320" class="mask"></canvas>
<div id="counter">
</div>
</div>
<br><div id="pic-holder" class="pull-left"><img id="screenshot"></div></br>
<input id="saveImage" type="button" value="save image" disabled="disabled"/>
</div>
</div>
</div>
</div>
The code is essentially taking the webcam stream and feeding it into a canvas element. Pressing the space button triggers a screenshot to be taken, which then appears as an image. Because I'm unable to provide the exact source of the file that is being downloaded the button only opens the image in another tab in the browser instead of functioning properly. I would really appreciate some input as to how I can resolve this. Thanks in advance.
I've already managed to do capture the stream from the canvas in an image with this bit of code:
document.addEventListener ('keydown', function (event) {
if(event.keyCode == 32) {
document.querySelector('#screenshot').src = canvas.toDataURL('image/webp')
}
})
What I want to know is how to enable the user to save the image onto their computer from there.
If I understand correctly you want to download (ie. provide a save dialog for the user to pick a location) the image to user's machine?'
If so you can use this snippet:
function download(canvas, filename) {
/// create an "off-screen" anchor tag
var lnk = document.createElement('a'),
e;
/// the key here is to set the download attribute of the a tag
lnk.download = filename;
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
lnk.href = c.toDataURL();
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
} else if (lnk.fireEvent) {
lnk.fireEvent("onclick");
}
}
Now all you need to do is to provide a default file name and call the function:
download(myCanvas, 'untitled.png');
If you rather than this mean save directly to user's harddisk then you can't due to security reasons.
That being said, there is always the option of using local storage such as File API or Indexed DB - but as these are sand-boxed you and the user will only have access to the "files" through the browser so perhaps not so convenient.
I don't think it's possible for IE without involving a server side script. Here's a good writeup on how to do it that way.
I had this problem and this is the best solution without any external or additional script libraries:
In Javascript tags or file create this function:
We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button.
Regarding the first task, you can export the canvas content to an image with toDataUrl method supported by the canvas object.
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d"); // Get the context for the canvas.
var myImage = canvas.toDataURL("image/png"); // Get the data as an image.
}
var image = document.getElementById("screenshot"); // Get the image object.
image.src = myImage;

Categories