Asp.net 文件下載

用時候當系統文件關聯直接下載的話會調用程序打開,或者想驗證後才能給用戶下載,那麼可以用這個方法實現

 private void FileDown(string strPath)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(strPath);
        if (file.Exists)
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.FullName, System.Text.Encoding.UTF8));
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Filter.Close();
            Response.WriteFile(file.FullName);
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(GetType(), "", "<script language='javascript'>alert('文件不存在!');</script>");
        }
    }

順便發一下打GridView轉成Excel讓用戶下載的代碼

private void DownExcel()
{
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=print.xls");
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
}

 
發佈了69 篇原創文章 · 獲贊 3 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章