对Ajax调用的响应与完全回发的响应不同

时间:2012-12-20 17:24:18

标签: asp.net ajax response

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

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实现同样的目标?

2 个答案:

答案 0 :(得分:1)

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

修改:这是一个Web窗体示例。自从我现在使用MVC以来,我的Web表单技能有点生疏;语法不在我的脑海中,所以你可能需要修改一下。

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.
}

答案 1 :(得分:1)

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

基本上你的ajax方法将无法处理接收文件,并且肯定没有权限将它组装并存储在你的硬盘上。

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

请检查此类似问题以获得答案。我已经粘贴了下面的答案。

starting file download with 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'。使用path作为get参数。我们认为这是最好的解决方案!

相关问题