繁体   English   中英

文件未在C#中下载

[英]File not Downloading in C#

我正在尝试下载由共享文件夹上的代码生成的文件。 文件已创建,当我尝试下载文件时,下载代码工作正常,但文件未在任何浏览器上下载。 下载按钮位于asp.net Update Panel此处是下载代码

try
{
    String contentType = String.Empty;
    FileInfo objFileInfo = null;

    this.FileMode = (DownloadFileMode)Session["FileMode"]; //DownloadFileMode.SingleFile;
    FileServerPath = ConfigurationManager.AppSettings["FileServerPath"];

    if (this.FileMode == DownloadFileMode.SingleFile)
    {
        if (Session["FileName"] != null)
        {
            FileName = Session["FileName"].ToString();
            contentType = "application/octet-stream";
            objFileInfo = new FileInfo(FileServerPath + FileName);
        }
        else
        {
            FileName = Session["SingleFile"].ToString();
            contentType = "application/octet-stream";
            objFileInfo = new FileInfo(FileServerPath + FileName);
        }
    }
    else if (this.FileMode == DownloadFileMode.ZippedFile)
    {
        FilesList = (List<String>)Session["FilesList"];
        contentType = "application/x-zip-compressed";
        if (FilesList.Count == 0)
            throw new Exception("No file to download");
        String strFilePath = String.Empty;
        String strZipPath = String.Empty;
        strZipPath = FileServerPath + "file" + CurrentUserSession.UserId.ToString() + "_" + CurrentUserSession.SessionId.ToString() + "_" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".zip";
        DownloadFiles(strZipPath, FilesList);
        objFileInfo = new FileInfo(strZipPath);
    }
    else
    {
        ScriptManager.RegisterStartupScript(this.Page, typeof(String), "MessageAlert", "alert('Invalid file mode');", true);
    }

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + objFileInfo.Name);
    Response.AddHeader("Content-Length", objFileInfo.Length.ToString());
    Response.ContentType = contentType;
    Response.TransmitFile(objFileInfo.FullName);
    //Response.End();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch(Exception ex)
{
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "MessageAlert", "alert('" + ex.Message + "');", false);
}

检查此代码。

    long sz = objFileInfo.Length;
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", 
    string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(objFileInfo)));
    Response.AddHeader("Content-Length", sz.ToString("F0"));
    Response.TransmitFile(objFileInfo);
    Response.End();

我认为您需要在UpdatePanel中添加以下触发器。

<Triggers>
<asp:PostBackTrigger ControlID="Your_Download_Button_ID">
</Triggers>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM