Home > Web Front-end > JS Tutorial > body text

How to Force Browser Downloads for Images Using Client-Side Programming?

Patricia Arquette
Release: 2024-11-09 05:56:02
Original
177 people have browsed it

How to Force Browser Downloads for Images Using Client-Side Programming?

Forcing Browser Downloads for Images Using Client-Side Programming

Background

When clicking on an Excel sheet or other downloadable files, browsers typically initiate the download process seamlessly. However, there is a need to replicate this behavior for image files specifically.

Implementing Image Downloads

Using client-side programming alone, you can achieve image downloads as follows:

document.onclick = function (e) {
    e = e || window.event;
    var element = e.target || e.srcElement;
    if (element.innerHTML == "Image") {
        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;
};

function saveImageAs1(name, address) {
    if (confirm('you wanna save this image?')) {
        window.win = open(address);
        setTimeout('win.document.execCommand("SaveAs")', 100);
        setTimeout('win.close()', 500);
    }
}
Copy after login

This code intercepts click events on the image element and prompts the user to save it using a Save As dialog box.

Case of Excel Downloads

In the case of Excel downloads, browsers handle the download process internally. They identify the file type based on the MIME type and trigger the appropriate download behavior without any additional programming.

HTML5 'download' Attribute

However, newer browsers support the 'download' attribute for elements, which provides a more convenient way to initiate image downloads:

<a href="http://localhost:55298/SaveImage/demo/abc.jpg" download>Image</a>
Copy after login

This attribute prompts the browser to download the image with the provided filename or the original filename, if not specified. Note that cross-origin downloads using this method are no longer supported as of 2018 due to security concerns.

The above is the detailed content of How to Force Browser Downloads for Images Using Client-Side Programming?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template