简体   繁体   中英

How to download a image on link click instead of opening it

I am running a flask app, and using a plugin named "Autoindex" for listing all the files in a directory, like this Now, when i click on an image name, it opens the image. But I want to downlaod the image without leaving the page on button click.

I cannot modify the HTML code of this. So I was thinking, can i use Javascript to perform this task?

EDIT

This is the HTML CODE:

<td class="name">
  <a href="/templete/images/2.jpg">2.jpg</a></td>
<td class="modified">
  <time datetime="2019-07-15 15:42:20.989829">2019-07-15 15:42:20.989829</time>
</td>
<td class="size">

Now, I cannot modify the HTML Code directly. The link has no class, how can I change this

<a href="/templete/images/2.jpg">2.jpg</a>

to this, for all image links in the page.

<a href="" download="/templete/images/2.jpg">2.jpg</a>

You can use JS to add download attribute to a HTML element:

element.setAttribute('download','')

Or even simpler:

element.download=''

So, you can easily add this for each link with a href ending .jpg :

const links=document.querySelectorAll('a[href$=".jpg"]')
links.forEach(link=>link.download='')

It is so easy! Put the image inside an tag or withing an tag then add the attribute download and the images' URL withing that tag. here is an example:

 <a href="https://www.publicdomainpictures.net/pictures/320000/nahled/background-image.png" download> <img src="https://www.publicdomainpictures.net/pictures/320000/nahled/background-image.png" alt="W3Schools" width="104" height="142"> </a>

image

Note: The download attribute is not supported in IE or Edge (prior version 18), or in Safari (prior version 10.1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM