我的问题类似于使用Ajax下载和打开pdf文件
但并非完全相同,我之所以想要一个JQuery ajax,是因为我的文件是从与同一页面获取的数据动态生成的。
因此,基本上我有一个Json对象需要发送到服务器,该服务器将动态生成一个文件并将其发送回浏览器。
我不想使用查询字符串将我的Json对象字符串化到锚点上,因为我认为这可能会存在潜在威胁,因为查询字符串具有字符限制(我在这里是正确的吗?)。
请告诉我我的工作流是否正确,或者我可以使用不同的流程实现相同的事情。
我的问题类似于使用Ajax下载和打开pdf文件
但并非完全相同,我之所以想要一个JQuery ajax,是因为我的文件是从与同一页面获取的数据动态生成的。
因此,基本上我有一个Json对象需要发送到服务器,该服务器将动态生成一个文件并将其发送回浏览器。
我不想使用查询字符串将我的Json对象字符串化到锚点上,因为我认为这可能会存在潜在威胁,因为查询字符串具有字符限制(我在这里是正确的吗?)。
请告诉我我的工作流是否正确,或者我可以使用不同的流程实现相同的事情。
不应该使用AJAX下载文件,这是无效的。也就是说,你只剩下两个选择:
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.
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" />
}
在页面中,您可以使用锚标签和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");
}
我也曾经为这个问题苦恼,上面的代码对我有用,希望能帮到你。
我的回答非常明确。在使用ajax请求服务器时,您无法下载PDF文件。因此,您应该使用HTML ActionLink。例如:
@Html.ActionLink("Convert Data into PDF", "PDFView", null, new { @class= "btn btn-info" });
FileResult
类返回PDF文件。
window.location = server\folder\filename
。我在这里使用 ASP.NET Web API。 - Leniel Maccaferri