【问题标题】:php code to download file not working with ajax [duplicate]用于下载文件的php代码不适用于ajax [重复]
【发布时间】:2013-12-05 11:27:55
【问题描述】:

我正在使用 ajax 调用 download.php 页面,但它无法正常工作。下面的代码中可能出现什么问题。

AJAX::

 $.ajax({
  type: "POST",
  url: 'downloadsample.php',
  data: {
  imagepath: "../ReportCard/imagepost.png"
  },
   success:function(data)   { 
    alert('sample download done ');
    }

    });

PHP 代码::

<?php

if ( isset($_POST["imagepath"]) && !empty($_POST["imagepath"]) ) { 
$file = $_POST['imagepath'];

    // Fetch the file info.
    if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
    }
    else {
        die('The provided file path is not valid.');
    }

}
    ?>

【问题讨论】:

    标签: php ajax


    【解决方案1】:

    您不能直接通过 ajax 下载文件。您可以将用户重定向到您的下载页面,也可以尝试使用 iframe。我的意思是使用隐藏的 iframe 或动态生成你喜欢的 iframe,并将这个 iframe 的源放到你的下载 URL 中。

    【讨论】:

    • i ajax 返回我应该创建 i 框架然后呢?
    • 您可以从 ajax 返回下载 url,并在 ajax 成功创建 iframe 并将该 url 放入 iframe 源
    【解决方案2】:

    您不能通过 Ajax 来执行此操作,因为 JavaScript 不能将文件直接保存到用户的计算机(出于安全考虑)。不幸的是,将主窗口的 URL 指向您的文件下载意味着您​​几乎无法控制文件下载发生时的用户体验。

    试试jQuery File Download,它允许文件下载的“类似Ajax”体验,并带有OnSuccess 和OnFailure 回调,以提供更好的用户体验。查看blog post 插件解决的常见问题以及使用它的一些方法以及demo of jQuery File Download 的实际应用。这是source

    这是一个简单的用例演示,使用带有 Promise 的插件 source。演示页面还包括许多其他“更好的 UX”示例。

     $.fileDownload('some/file.pdf')
        .done(function () { alert('File download a success!'); })
        .fail(function () { alert('File download failed!'); });
    

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多