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

Sak*_*maa 20 html safari internet-explorer hyperlink web

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

<a href="img.jpg" download="img.jpg">Download Image</a>
Run Code Online (Sandbox Code Playgroud)

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

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

Nic*_*nia 14

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

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{QUERY_STRING} fdl=1
RewriteRule .? - [T=application/octet-stream]
Run Code Online (Sandbox Code Playgroud)

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

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

<a href="img.jpg?fdl=1">Download Image</a>
Run Code Online (Sandbox Code Playgroud)

要在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>
Run Code Online (Sandbox Code Playgroud)

编辑(2016年10月4日):

看起来所有浏览器仍未完全采用download属性.

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