0

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

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=">

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

4

2 回答 2

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>

下面的链接是带有文件名和分机下载属性的演示

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

注意:下载属性不受广泛支持

于 2013-10-04T06:55:12.237 回答
1

JavaScript 无法保存文件,因此在这种情况下,您需要url从您的APIthensuccess函数中返回 a,您将使用window.location = ....returned value...this 来下载文件。

如果需要演示,请告诉我。

于 2013-10-04T06:58:21.090 回答