在.net Web表单应用程序中使用ajax下载文件

时间:2017-05-16 10:59:11

标签: c# asp.net ajax

我正在使用.net网络表单应用程序,我在按钮点击(使用ajax)下载excel文件,因为我创建了类

public class ImunizattionHelper
    {
        public void DownloadFile(String FileTitle,String FilePath)
        {
            HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
            String Header = "Attachment; Filename=" + FileTitle;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
            System.IO.FileInfo Dfile = new System.IO.FileInfo(FilePath);
            HttpContext.Current.Response.WriteFile(Dfile.FullName);
            HttpContext.Current.Response.End();
        }
    }

我点击按钮

调用此WebMethod
 [WebMethod]
        public static void ExportChildernsToExcel(string districtID, string districtName)
        {
            ImunizattionHelper helper = new ImunizattionHelper();
            helper.DownloadFile(districtName + "_Childrens.xlsx", HttpContext.Current.Server.MapPath("~/ExcelBackup/FileToDownload/DistrictwiseChildrens.xlsx").ToString());
        }

AJAX

 $("#btn_ExportChildernData").click(function () {

             $.ajax({
                 url: 'ExportChildrenToExcel.aspx/ExportChildernsToExcel',
                 type: 'POST',
                 dataType: 'json',
                 contentType: 'application/json; charset=utf-8',
                 data: "{ districtID: '" + $("#MainContent_ddlDistrictName option:selected").val() + "', districtName: '" + $("#MainContent_ddlDistrictName option:selected").text() + "' }",
                 success: function (msg) {

                 },
                 error: function (XMLHttpRequest, textStatus, errorThrown) {
                     alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
                 }
             });
         })

但这会在此代码上产生错误

HttpContext.Current.Response.End();

并且文件下载不起作用。并生成错误。

Click to See Error

但如果我使用aspx:按钮并在按钮点击事件上使用此代码(我的意思是没有ajax)

<asp:Button ID="ExportChildernData" runat="server" Text="Export Childern Data To Excel" OnClick="ExportChildernData_Click" />
 protected void ExportChildernData_Click(object sender, EventArgs e)
        {   
            ImunizattionHelper helper = new ImunizattionHelper();
            helper.DownloadFile(ddlDistrictName.SelectedItem.Text+"_Childrens.xlsx", HttpContext.Current.Server.MapPath("~/ExcelBackup/FileToDownload/DistrictwiseChildrens.xlsx").ToString());

        }

一切正常

我的问题是为什么文件下载不适用于ajax?从Web表单应用程序中的特定路径下载excel文件的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

我是怎么做的将文件保存在缓存

Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender

    Dim excelStream As MemoryStream
    Dim excelFilename As String
    excelStream = CType(Cache("ExcelViewerContent"), MemoryStream)
    excelFilename = CType(Cache("ExcelViewerFilename"), String)

    Response.ClearContent()
    Response.Clear()
    Response.Buffer = True
    Response.Charset = ""
    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache)
    Response.AddHeader("content-disposition", Convert.ToString("attachment; filename=") & excelFilename)
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.BinaryWrite(excelStream.ToArray())
    Response.Flush()
    HttpContext.Current.ApplicationInstance.CompleteRequest()

End Sub

然后将它们发送到名为“ExcelViewer.aspx”的新页面,然后在PreRender中我有这个:

$('.table a').click(function() {
    $(this).parent('.table').next('.info').toggle();
});

原谅VB代码。工作良好。

答案 1 :(得分:0)

为什么不使用 FileContentResult

{{1}}