强制浏览器在单击时下载图像文件 [英] Force browser to download image files on click

查看:29
本文介绍了强制浏览器在单击时下载图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要浏览器下载图像文件,就像点击 Excel 工作表一样.

I need the browser to download the image files just as it does while clicking on an Excel sheet.

有没有办法只使用客户端编程来做到这一点?

Is there a way to do this using client-side programming only?

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript" src="Scripts/jquery-1.10.2.js">
        $(document).ready(function () {
            $("*").click(function () {
                $("p").hide();
            });
        });
        </script>
    </head>

    <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;
        };

        function saveImageAs1(name, adress) {
            if (confirm('you wanna save this image?')) {
                window.win = open(adress);
                //response.redirect("~/testpage.html");
                setTimeout('win.document.execCommand("SaveAs")', 100);
                setTimeout('win.close()', 500);
            }
        }
    </script>

    <body>
        <form id="form1" runat="server">
            <div>
                <p>
                    <a href="http://localhost:55298/SaveImage/demo/Sample2.xlsx" target="_blank">Excel</a><br />
                    <a href="http://localhost:55298/SaveImage/demo/abc.jpg" id="abc">Image</a>
                </p>
            </div>
        </form>
    </body>
</html>

</表单>

How should it work in case of downloading an Excel sheet (what browsers do)?

在下载 Excel 表格的情况下它应该如何工作(浏览器可以做什么)?

解决方案

推荐答案

使用 HTML5,您可以将下载"属性添加到您的链接中.

<a href="/path/to/image.png" download>

兼容的浏览器将提示下载具有相同文件名的图像(在本例中为 image.png).

If you specify a value for this attribute, then that will become the new filename:

如果您为此属性指定一个值,那么它将成为新的文件名:

<a href="/path/to/image.png" download="AwesomeImage.png">

这篇关于强制浏览器在单击时下载图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆