使用ajax调用从服务器文件夹下载图像

时间:2020-04-26 15:35:26

标签: php jquery ajax

我有一个在大多数情况下都使用ajax的网站。我已经允许用户通过ajax上传图像。当用户单击按钮时,通过ajax调用以模态显示图像。

现在,我要用户通过单击图像开始下载而不关闭模态或刷新。我确实尝试过使用href。它工作正常,但是,正如我提到的,我想让用户保持模式打开的状态在同一页面上。

直到现在我一直尝试的代码是:

$(document).ready(function(){
    var imgname;
    imgname = '';
    $("#modalimage").click(function(){
        imgname = $("#downloadimg").val();
        downloadImage(imgname);
    })
})
function downloadImage(imagename){
    $.ajax({
            type : "POST",
            url : "download.php",
            data : { imagename : imagename } ,
            success : function(response){
                alert('success');
            }
    })
}

download.php 代码为:

if ( isset($_POST['imagename']) ) {
    $filename = $_POST['imagename'];
    $filepath = 'images/'.$filename;
}
echo $filepath;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);

这里的问题是,当ajax调用download.php时,它会以一些二进制代码和小图像代码的形式创建响应,而没有启动下载。是否可以通过ajax调用下载图像?

here is the image

1 个答案:

答案 0 :(得分:2)

而不是通过ajax调用该链接:

or

其中$ imagename是文件路径。链接内容可以是文本,缩略图或任何您想要的内容。

只需更改download.php代码以通过$ _GET而不是$ _POST获取图像,并且重要的是删除其中存在的回声,除了标头和文件内容:

select(.level == "info" or .msg == "end")

您将不会重定向到该文件,而是将下载该文件。不需要使用ajax。

如果您真的更喜欢使用javascript,则可以创建动态链接:

<a href="download.php?imagename=<?php echo urldecode($imagename); ?>">
    Clich here to download
</a>