C#文件下载方法

2021-04-18 13:28

阅读:415

    

 

    

//

第二:WriteFile下载文件

string fileName ="asd.txt";//

客户端保存的文件名

string filePath=Server.MapPath("DownLoad/aaa.txt");//路径 

FileInfo fileInfo = new FileInfo(filePath); 

Response.Clear();    

Response.ClearContent();       

Response.ClearHeaders();       

Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);       

Response.AddHeader("Content-Length", fileInfo.Length.ToString());      

Response.AddHeader("Content-Transfer-Encoding", "binary");     

Response.ContentType = "application/octet-stream"; 

Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 

Response.WriteFile(fileInfo.FullName); 

Response.Flush();    

Response.End(); 

 

三:流方式下载

FileStream fs = new FileStream(filePath, FileMode.Open); 

byte[] bytes = new byte[(int)fs.Length];   

fs.Read(bytes, 0, bytes.Length);  

fs.Close(); 

Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开

Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); 

Response.BinaryWrite(bytes); 

Response.Flush();   

Response.End();


评论


亲,登录后才可以留言!