如何使Safari和IE下载图像而不是在新页面中打开?

问题描述 投票:20回答:4

在Firefox和Chrome中,此链接属性“download = img.jpg”工作正常,并显示下载窗口而不是新的选项卡或页面。

<a href="img.jpg" download="img.jpg">Download Image</a>

但在Safari和IE中,这个链接给了我一个新的页面。

那么使用Safari和IE浏览器处理这个问题的简单而有效的工作流程是什么?

html internet-explorer web hyperlink safari
4个回答
14
投票

你在Apache服务器上工作吗?如果是这样,您可以将其添加到.htaccess文件中:

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{QUERY_STRING} fdl=1
RewriteRule .? - [T=application/octet-stream]

检查是否为文件检查参数fdl = 1是否在querystring输出为octet-stream / force下载

现在,当您希望浏览器开始下载该站点中的任何内容时,只需将参数放在URL上:

<a href="img.jpg?fdl=1">Download Image</a>

要在IIS Windows服务器上执行相同的操作,请将出站规则添加到web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <outboundRules>
                <rule name="Force Download">
                    <match serverVariable="RESPONSE_Content_Disposition" pattern=".?" negate="false" />
                    <action type="Rewrite" value="application/octet-stream" replace="true" />
                    <conditions>
                        <add input="{QUERY_STRING}" pattern="fdl=1" />
                    </conditions>
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>

编辑(2016年10月4日):

所有浏览器看起来download属性仍然是not fully adopted

对于基于JavaScript /浏览器的实现,您可以查看FileSaver.js,它是一个polyfill,用于在不支持它的浏览器中保存功能。虽然它没有完美的覆盖范围。


0
投票

这是一种使用JavaScript在IE中执行此操作的方法。但是,我找不到Safari的解决方案了

var canvas = document.createElement('canvas');
var img = document.createElement('img');
img.onload = function(e) {
    canvas.width = img.width;
    canvas.height = img.height;
    var context = canvas.getContext('2d');
    context.drawImage( img, 0, 0, img.width, img.height);
    window.navigator.msSaveBlob(canvas.msToBlob(),'image.jpg');
}
img.src = 'img.jpg;

-1
投票

最简单的方法是使用像PHP这样的服务器端语言。本页面对此进行了更深入的讨论,包括一些用于操作标题的试用代码等。不幸的是,在IE和Safari迎头赶上之前,这些是唯一的解决方案。

参考:


-1
投票
navigator.msSaveBlob(blob, filename)

https://msdn.microsoft.com/sv-se/library/windows/apps/hh772331

不幸的是我不知道如何在Safari中做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.