0

当我尝试使用回发以下代码时,文件下载正常进行:

FileInfo file = new FileInfo("C:\\a.txt");
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.TransmitFile(file.FullName);
Response.End();

但是,如果我将上述代码放在公共静态 Web 方法中并使用 AJAX 调用它,我会收到错误消息,例如“进程被中止”。(当然要获得当前响应,我会写 HttpContext.Current.Response)这让我想到这两种反应的性质是不同的。我的问题是,如果它们不同,那么到底有什么不同?有没有办法用 AJAX 实现同样的目标?

4

2 回答 2

1

浏览器不会通过 XHR (Ajax) 调用接收文件。您需要返回文件位置,然后通过window.location或将浏览器发送到该文件window.open

编辑:这是一个 Web 表单示例。自从我现在使用 MVC 以来,我的 Web Forms 技能有点生疏了;语法不在我的脑海中,因此您可能需要对其进行一些修复。

ASPX 页面

<div id="whateverIsContainingYourDialog">
    <form id="mikeJMIsAwesome" runat="server">
        <asp:TextBox id="firstName" runat="server" />
        <asp:TextBox id="lastName" runat="server" />

        <asp:Button id="submit" runat="server" />
    </form>
</div>

服务器端代码

protected void submit_OnClick(object sender, EventArgs e) {
    //Your logic for creating the file and the code you originally posted for serving the file.
}
于 2012-12-20T17:28:08.323 回答
1

Ek0nomik 说,文件下载由浏览器处理,无法通过 Javascript 处理。响应都是相同的,它们都只是 http 响应 - 您可以使用 fiddler 或其他工具(http://www.fiddler2.com/fiddler2/)来验证这一点。

本质上,您的 ajax 方法将无法处理接收文件,并且肯定无权组装它并将其存储在您的硬盘上。

您可以使用一些 Javascript 来“伪造”点击链接的用户。

请检查这个类似的问题以获得答案。我已将答案粘贴在下面。

使用 JavaScript 开始文件下载

我们这样做:首先添加这个脚本。

<script type="text/javascript">
function populateIframe(id,path) 
{
    var ifrm = document.getElementById(id);
    ifrm.src = "download.php?path="+path;
}
</script>

把它放在你想要下载按钮的地方(这里我们只使用一个链接):

<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
The file 'download.php' (needs to be put on your server) simply contains:

<?php 
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

因此,当您单击链接时,隐藏的 iframe 会获取/打开源文件“download.php”。使用路径作为获取参数。我们认为这是最好的解决方案!

于 2012-12-20T17:50:53.580 回答