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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
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:Test Request:
Test Response:
HTML5 Solution
You can use the HTML5
download
attribute on anchors:I have come up with pure JavaScript way to force download of image, with the following restrictions:
The above restrictions (especially the third) more or less renders this useless but still, the "core" idea is working and hopefully at some point in the future it will be possible to determine file name then it will become much more useful.
Here is the code:
As you can see, the trick is drawing the image into
canvas
object, get the raw binary data of the image then force download by usingimage/octet-stream
mime type and changing the browser location.Usage sample follows as well.
HTML:
JavaScript:
This allows to "attach" download button to every existing image by assigning the
rel
attribute of the button to the image ID - the code will do the rest and attach the actual click events.Due to the same origin policy can't post live example at jsFiddle - they're using "sandbox" domain to execute the scripts.
I'm guessing you mean something like this:
Go to url in browser, URL is: http://example.com/image.png
and instead of displaying, the browser prompts you to save the image?
I'm fairly certain that you cannot force this with javascript and will need a server-side language to control headers. And even at that point you cannot FORCE the browser to download it, each useragent will react differently to whatever headers you may send.
EDIT: I seem to remember the header being
Content-Disposition: attachment;
Here's a simple solution that uses the HTML5 'download' attribute:
This is totally possible. Just encode the image as Base64 then do a
window.open
with adata:image/jpg,Base64,...
-style url.