ASP.net 文件下載

只谈情不闲聊 提交于 2020-01-23 07:52:11
用时候当系统文件关联直接下载的话会调用程序打开,或者想验证后才能给用户下载,那么可以用这个方法实现

 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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!