使用 Javascript 强制下载图像 [英] Force Download an Image Using Javascript

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

问题描述

我想知道是否有任何方法可以使用 Javascript/jQuery 制作脚本来下载(打开下载对话框)图像,以便浏览器不只是显示它.

I want to know if there is any way to make a script using Javascript/jQuery to download (open a download dialog) a image so the browser won't just show it.

推荐答案

您需要为此使用服务器端脚本.在 stackoverflow 上搜索.

You need to use server-side scripting for this. Search on stackoverflow.

或者,您的服务器可能允许您通过配置动态更改标头.

Alternately, your server might allow you to alter headers dynamically via configuration.

将可下载的图像放在一个目录中.在这个目录中,创建一个 .htaccess 文件,内容如下:

Place your downloadable images in a directory. Inside this directory, create a .htaccess file with the following contents:

SetEnvIf Request_URI "([^/]+.jpg)$" REQUESTED_IMAGE_BASENAME=$1
SetEnvIf Request_URI "([^/]+.png)$" REQUESTED_IMAGE_BASENAME=$1
Header set Content-Disposition "attachment; filename="%{REQUESTED_IMAGE_BASENAME}e"" env=REQUESTED_IMAGE_BASENAME

测试请求:

HEAD /test/Water%20lilies.jpg HTTP/1.1
Host: localhost

测试响应:

HTTP/1.1 200 OK
Date: Sat, 23 Jul 2011 09:03:52 GMT
Server: Apache/2.2.17 (Win32)
Last-Modified: Thu, 23 Aug 2001 14:00:00 GMT
ETag: "26000000017df3-14752-38c32e813d800"
Accept-Ranges: bytes
Content-Length: 83794
Content-Disposition: attachment; filename="Water lilies.jpg"
Content-Type: image/jpeg

HTML5 解决方案

您可以使用 HTML5 download锚点上的属性:

HTML5 Solution

You can use the HTML5 download attribute on anchors:

<p>Example 1<br>
   <a href="http://dummyimage.com/600x400/000/fff.png" download>Download this image</a></p>

<p>Example 2<br>
   <a href="http://dummyimage.com/600x400/000/fff.png" download="alternate-filename.png"><img
       src="http://dummyimage.com/150x100/000/fff.png"></a></p>

这篇关于使用 Javascript 强制下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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