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

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

问题描述

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

您需要为此使用服务器端脚本。 在计算器上搜索



或者,您的服务器可能允许你通过配置动态地改变头部。

使用mod_headers的Apache解决方案



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


$ b

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

测试要求:

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

测试回应:$ b $

HTTP / 1.1 200 OK
日期:2011年7月23日(星期六)09:03:52 GMT
服务器:Apache / 2.2.17(Win32)
上次修改时间:星期四,2001年8月23日14:00:00 GMT
ETag:26000000017df3-14752-38c32e813d800
接受范围:字节
Content-Length:83794
Content-Disposition:attachment;文件名=Water lilies.jpg
Content-Type:image / jpeg


$ b

HTML5解决方案



您可以使用锚点上的HTML5 下载属性
$ b

 < p>示例1< br> < a href =http://dummyimage.com/600x400/000/fff.png下载>下载此图片< / a>< / p>< p>示例2< br> < a href =http://dummyimage.com/600x400/000/fff.pngdownload =alternate-filename.png>< img src =http://dummyimage.com/150x100/000 /fff.png\"> /lt;/a></p>  


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.

解决方案

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

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

Apache solution with mod_headers

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

Test Request:

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

Test Response:

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 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天全站免登陆