Asp.net C# 檔案下載,附件下載程式碼案例,不顯示檔案路徑

龐順龍發表於2019-05-11

Asp.net C# 檔案下載,附件下載程式碼案例

本案例是以檔案流的方式將檔案下載到瀏覽器,瀏覽器自動彈出下載提示框,不顯示檔案絕對路徑,適合做積分下載等。

try
{
    string fileid = ObjectHandlers.Get("fileid").ToString();
    //獲取下載的檔案資訊
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Model.FileInfo modelFileInfo = bllFileInfo.GetFileByFileID(fileid);
    
    if (modelFileInfo != null)
    {
        System.IO.FileInfo downloadFile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath("../" + modelFileInfo.FilePath));
        if (downloadFile.Exists)
        {            
		///指定返回的是一個不能被客戶端讀取的流,必須被下載
		HttpContext.Current.Response.ContentType = "application/octet-stream";
		HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
		///新增頭資訊,為"檔案下載/另存為"對話方塊指定預設檔名 
		//Response.AddHeader("Content-Disposition", "attachment;  filename=" + fileName);
		HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" 
			+ HttpUtility.UrlEncode(downloadFile.Name, System.Text.Encoding.UTF8));
		///是否要支援斷點續傳
		HttpContext.Current.Response.AddHeader("Content-Range", "bytes 0-800/801");
		///新增頭資訊,指定檔案大小,讓瀏覽器能夠顯示下載進度 
		HttpContext.Current.Response.AddHeader("Content-Length", downloadFile.Length.ToString());
		HttpContext.Current.Response.TransmitFile(downloadFile.FullName);
		//HttpContext.Current.Response.End(); 
		HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        else
        {
            string contentType = "text/html; charset=utf-8";
            return Response.AsText("下載失敗,原始檔不存在!", contentType);
        }
    }
    else
    {
        string contentType = "text/html; charset=utf-8";
        return Response.AsText("下載失敗,原始檔不存在!", contentType);
    }
    return null;
}
catch (Exception ex)
{
    string contentType = "text/html; charset=utf-8";
    return Response.AsText("系統異常導致下載失敗,請重新嘗試下載!", contentType);
}


有問題可以進群提問~

龐順龍最後編輯於:4年前

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章