如何强制图像被下载? [英] How to force an image to be downloaded?

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

问题描述

我在我的页面上哈瓦一个动态生成的图像,像这样:

I hava a dynamically generated image on my page like so:

<img id="my_image" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEA/gD+AAD/etc............" />

不是告诉我的用户右键点击图片,并点击保存我要揭露,点击后提示要下载的图像的下载链接。如何实现这一目标?

Instead of telling my users to right click on the image and hit save I want to expose a download link which when clicked will prompt the image to be downloaded. How to achieve this?

起初我试图用这样的JS:

Initially my attempt with thus in js:

var path = $('#my_image').attr('src');
window.open('./download.php?file=' + path);

和中的download.php:

and in download.php:

<?php
    header('Content-Description: File Transfer');
    header("Content-type: application/octet-stream");
    header("Content-disposition: attachment; filename= " . $_GET['file'] . "");
?>

<img src="<?= $_GET['file'] ?>" />

但问题是,Base64编码的url stirngs是如此之大,它超过了GET请求字节的限制。

But problem is, Base64 url stirngs are so large it exceeds the GET request byte limit.

我打开JavaScript或PHP的解决方案。

I am open to a solution in either JavaScript or PHP.

推荐答案

原来的其他问题一个也有了答案:

Turns out one of the other questions did have the answer:

<一个href=\"http://stackoverflow.com/questions/10473932/browser-html-force-download-of-image-from-src-dataimage-jpegbase64\">Browser/HTML从图像的力量下载SRC =&QUOT;数据:图像/ JPEG;的base64 ...&QUOT;

我严格做像这样的客户端SDE:

I am doing it strictly on the client sde like so:

$('a#download_image').on('click', function() {
    var url = $('#my_image').attr('src').replace(/^data:image\/[^;]/, 'data:application/octet-stream');
    location.href = url;
});

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

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