【问题标题】:download image from server folder using ajax call使用ajax调用从服务器文件夹下载图像
【发布时间】:2020-04-26 15:35:26
【问题描述】:

我的网站在大多数情况下都使用 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调用下载图片吗?

【问题讨论】:

  • 据我了解,你想通过AJAX上传图片文件,对吧?
  • 我已经用 ajax 调用上传了图像。现在我想通过 ajax 调用来下载该图像
  • 好的,所以您希望您的用户能够通过 AJAX 下载图像文件,对吧?
  • 我这里没有显示重定向代码...我想通过制作 ajax 来下载...我想我没有把我的问题说清楚

标签: php jquery ajax


【解决方案1】:

不要通过 ajax 调用它,而是放置这个链接:

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

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

只需更改 download.php 代码以通过 $_GET 而不是 $_POST 获取图像,重要的是,删除那里的回声,除了标题和文件内容:

if ( isset($_GET['imagename']) ) {
    $filename = $_GET['imagename'];
    $filepath = 'images/'.$filename;
}
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。

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

$(document).ready(function(){
    $("#modalimage").click(function(){
        var imgname = $("#downloadimg").val();
        var link = document.createElement("a");
        link.download = name;
        link.href = 'download.php?imagename=' + encodeURI(imgname);
        link.click();
    });
})

【讨论】:

  • 我已经使用了锚标签...但是当我第一次使用它时它重定向到 download.php 是因为我忘记删除的 echo $filepath..?我会弄清楚。但是感谢您的帮助
  • 是的,回显是在发送任何标头之前,并且由于没有用于下载的标头,因此 URL 被重定向。没问题,我很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2017-08-06
  • 2011-06-04
  • 2012-07-08
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2017-08-11
相关资源
最近更新 更多