簡體   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