Guest User

Force Download an Image Using Javascript

a guest
Apr 8th, 2012
512
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. SetEnvIf Request_URI "([^/]+.jpg)$" REQUESTED_IMAGE_BASENAME=$1
  2. SetEnvIf Request_URI "([^/]+.png)$" REQUESTED_IMAGE_BASENAME=$1
  3. Header set Content-Disposition "attachment; filename="%{REQUESTED_IMAGE_BASENAME}e"" env=REQUESTED_IMAGE_BASENAME
  4.  
  5. HEAD /test/Water%20lilies.jpg HTTP/1.1
  6. Host: localhost
  7.  
  8. HTTP/1.1 200 OK
  9. Date: Sat, 23 Jul 2011 09:03:52 GMT
  10. Server: Apache/2.2.17 (Win32)
  11. Last-Modified: Thu, 23 Aug 2001 14:00:00 GMT
  12. ETag: "26000000017df3-14752-38c32e813d800"
  13. Accept-Ranges: bytes
  14. Content-Length: 83794
  15. Content-Disposition: attachment; filename="Water lilies.jpg"
  16. Content-Type: image/jpeg
  17.  
  18. function DownloadImage(imageURL) {
  19. var oImage = document.getElementById(imageURL);
  20. var canvas = document.createElement("canvas");
  21. document.body.appendChild(canvas);
  22. if (typeof canvas.getContext == "undefined" || !canvas.getContext) {
  23. alert("browser does not support this action, sorry");
  24. return false;
  25. }
  26.  
  27. try {
  28. var context = canvas.getContext("2d");
  29. var width = oImage.width;
  30. var height = oImage.height;
  31. canvas.width = width;
  32. canvas.height = height;
  33. canvas.style.width = width + "px";
  34. canvas.style.height = height + "px";
  35. context.drawImage(oImage, 0, 0, width, height);
  36. var rawImageData = canvas.toDataURL("image/png;base64");
  37. rawImageData = rawImageData.replace("image/png", "image/octet-stream")
  38. document.location.href = rawImageData;
  39. document.body.removeChild(canvas);
  40. }
  41. catch (err) {
  42. document.body.removeChild(canvas);
  43. alert("Sorry, can't download");
  44. }
  45.  
  46. return true;
  47. }
  48.  
  49. <image id="myimage" src="Penguins.jpg" />
  50. <button type="btnDownload" rel="myimage">Download</button>
  51.  
  52. window.onload = function() {
  53. var arrButtons = document.getElementsByTagName("button");
  54. for (var i = 0; i < arrButtons.length; i++) {
  55. var oButton = arrButtons[i];
  56. var sRelatedImage = oButton.getAttribute("rel");
  57. if (sRelatedImage && sRelatedImage.length > 0) {
  58. oButton.onclick = function() {
  59. HandleRelatedImage(this, sRelatedImage);
  60. }
  61. }
  62. }
  63. };
  64.  
  65. function HandleRelatedImage(oButton, sRelatedImage) {
  66. var oImage = document.getElementById(sRelatedImage);
  67. if (!oImage) {
  68. alert("related image '" + sRelatedImage + "' does not exist");
  69. return false;
  70. }
  71.  
  72. return DownloadImage(sRelatedImage);
  73. }
  74.  
  75. var myImage = new Image();
  76. myImage.src = "http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif";
Add Comment
Please, Sign In to add comment