JQuery Ajax调用以下载PDF文件

9

我的问题类似于使用Ajax下载和打开pdf文件

但并非完全相同,我之所以想要一个JQuery ajax,是因为我的文件是从与同一页面获取的数据动态生成的。

因此,基本上我有一个Json对象需要发送到服务器,该服务器将动态生成一个文件并将其发送回浏览器。

我不想使用查询字符串将我的Json对象字符串化到锚点上,因为我认为这可能会存在潜在威胁,因为查询字符串具有字符限制(我在这里是正确的吗?)。

请告诉我我的工作流是否正确,或者我可以使用不同的流程实现相同的事情。

3个回答

8

不应该使用AJAX下载文件,这是无效的。也就是说,你只剩下两个选择:

  1. action link and query string parameters or if the download must be trigerred at some specific javascript event you could also set the window.location.href to the action that is supposed to generate the PDF file and pass query string parameters to it.

  2. or if you are afraid that you have lots of data to pass to the controller action that will generate the PDF to download you use a <form> with method="POST" and inside you use hidden fields to store as much parameters and data as you like:

    @using (Html.BeginForm("download", "home"))
    {
        ... hidden fields containing values that need to be sent to the server
        <input type="submit" value="Download PDF" />
    }
    

Darin:你觉得使用 AJAX GET 请求在服务器上生成文件怎么样?这样可以在失败回调中捕获在文件生成期间发生的任何错误并显示给用户。如果成功,我会将文件名传递给 AJAX 成功回调,然后执行 window.location = server\folder\filename。我在这里使用 ASP.NET Web API。 - Leniel Maccaferri
OP特别要求使用ajax。这样做会浪费带宽。 - CodeWarrior
@OmarPadilla,你不能使用AJAX将文件下载到客户端。但即使可能,你也会浪费与直接链接下载文件完全相同的带宽。简单的原因是,在两种情况下,你都在调用返回相同文件的服务器上的同一端点。而且不要被骗以为如果你不使用AJAX,当前页面将重新加载。除了流式传输文件的控制器操作之外,没有其他额外的请求。 - Darin Dimitrov
为什么不应该使用Ajax下载文件?https://dev.to/nombrekeff/download-file-from-blob-21ho - Alex78191

0

在页面中,您可以使用锚标签和PHP强制下载来执行PDF下载,而不是在页面中进行一次额外的ajax调用。

HTML
    <a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>

PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }
    readfile($fullPath);
    exit;
}
?>

我正在检查文件大小,因为如果您从CDN CloudFront加载PDF,则无法获取文档的大小,这会导致文档以0kb下载。为了避免这种情况,我正在使用此条件进行检查。

  if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }

我也曾经为这个问题苦恼,上面的代码对我有用,希望能帮到你。


2
好的回答,尽管与 ASP.NET 标签不太相关。 - lucasreta

0

我的回答非常明确。在使用ajax请求服务器时,您无法下载PDF文件。因此,您应该使用HTML ActionLink。例如:

@Html.ActionLink("Convert Data into PDF", "PDFView", null, new { @class= "btn btn-info" });

以上代码将生成一个链接按钮,您可以访问控制器的动作方法。此外,您可以使用任何技术从控制器返回PDF文件,例如,您可以使用FileResult类返回PDF文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接