以代码格式下载图像

时间:2013-10-04 06:52:28

标签: javascript php download imagedownload

我试图制作一个下载图像的按钮,我做的是,做了这样的功能:

function download_image(){
    $file = $_POST['file'];
    header('Content-Description: File Transfer');
    header("Content-type: application/octet-stream");//notice this content-type, it will force a download since browsers think that's what they should do with .exe files
    header("Content-disposition: attachment; filename= ".$file."");
    readfile($file);
}

当点击下载按钮时,我执行了这个js:

$.ajax({
        type:"POST",
        url:'..address to../download_image',
        data:{
            file:imgElem
        },
        success:function(){
            alert('image downloaded');
        }
    });

现在问题是我没有图像名称,但编码图像是这样的:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABBgAAAEtCAYAAACibtPQAAAgAElEQVR4nO3dX28c150mYH+c+S57s5d7uVcFGMEGuQiwgW+ycCEAsdl4gQjGJqsyYIyCYEbwEDXKZD1KNLHVtjMZDeM/kmmWLJmOrSiOzViOJDJiHNtnLoLqLRarm8VDFfsU63mBBzabzWZ12/rp1MtTzSdCCKEoipBlWciyLFRVFbpSVdX8PlmWhTzPO+8nIiIiIiIiItPLE7PZLJRlGUIIoSzLUBRF5x3rgkFEREREREREpJ0nmh8oGEREREREREQkJvOCIc/z+U6GrrQvkVh2XxERERERERGZVo61g6H+nN0MIiIiIiIiItLME+0b+hYHy94QUkRERERERESmlSfKsgyz2SyEEMJsNjvw2yHyPO/c0WAHg4iIiIiIiIg080QIi39NZbNgaL8HQ11KiIiIiIiIiIgcukRCREREREREROS4UTCIiIiI...PHWSgveiOXekFY/8Rr2ZBZ9hO1+vu2t8Mt+7r2Frr2X0JH3Z7n+aECob3Ntvn1zeNoP+/2cXY9FwWDSNqZwtzsWqDX861rV8NRBUP99V3zc9G8zfN8/vXtOdr1NUct1tvPXUTis2iXQAiH3xCwvTOrOQOan2+v15pf03WSuuj71DOjXYC014Lt+3Z97xC6d2097ufSTvuyjeZusaMe9yQFQ/Pxu55L83gf5/OVdKNgkDORRdvRRESkO6c1N+tLMeos2sorIiIi44+CQUadrsZZREQW57TnZv0TKDsCREREzn4UDCIiIiIiIiJy4igYREREREREROTEUTCIiIiIiIiIyImjYBARERERERGRE0fBICIiIiIiIiInjoJBRERERERERE4cBYOIiIiIiIiInDgKBhERERERERE5cRQMIiIiIiIiInLiKBhERERERERE5MRRMIiIiIiIiIjIiaNgEBEREREREZET5z8AyGKspBK3ENIAAAAASUVORK5CYII=">

所以问题是我应该如何下载图像?请帮忙:(

2 个答案:

答案 0 :(得分:2)

只需将window.location设置为已编码的 URI ,例如

window.location.href = 'data:image/png;base64,iVBORw0KGgo...

或者你也可以打开一个弹出窗口

http://jsfiddle.net/vaibviad/VE8Qn

如果您想拥有文件名和扩展名,那么您也可以尝试使用

<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>

以下链接是带有filename和ext

的下载属性的demo

http://jsfiddle.net/vaibviad/VE8Qn/3/

注意:Download attribute不受广泛支持

答案 1 :(得分:1)

JavaScript无法保存文件,因此在这种情况下,您需要从url返回API,然后在success函数中返回window.location = ....returned value...这个将下载该文件。

如果需要DEMO,请告诉我。