C# ASP 上传/下载文件
Posted 惊涛拍岸,风卷残云,指端似有雄兵百万
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# ASP 上传/下载文件相关的知识,希望对你有一定的参考价值。
1. 上传文件前台页面
1 <div style="padding-left:20px;"> 2 <asp:FileUpload ID="FileUpload1" runat="server" style="width:400px;"/> 3 <asp:Button ID="Button1" runat="server" OnClick="Upload_Click" Text="上传" style="width:65px;height:22px"></asp:Button > 4 </div>
上传文件后台代码
1 private string _directory = @"../Questionnaire35"; 2 3 protected void Upload_Click(object sender, EventArgs e) 4 { 5 try 6 { 7 if (Request.Files.Count > 0) 8 { 9 if (string.IsNullOrEmpty(Request.Files[0].FileName)) 10 { 11 return; 12 } 13 //判断文件大小 14 int length = Request.Files[0].ContentLength; 15 if (length > 1048576) 16 { 17 Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert(‘文件大于1M,不能上传‘);</script>"); 18 return; 19 } 20 21 string type = Request.Files[0].ContentType; 22 string fileExt = Path.GetExtension(Request.Files[0].FileName).ToLower(); 23 //只能上传图片,过滤不可上传的文件类型 24 string fileFilt = ".xlsx|.xls|.docx|.doc|......"; 25 if (fileFilt.IndexOf(fileExt) <= -1) 26 { 27 Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert(‘只能上传文档‘);</script>"); 28 return; 29 } 30 else 31 { 32 UserInfo user = (UserInfo)Session["UserInfo"]; 33 //string fileName = Server.MapPath(_directory) + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileExt; 34 string fileName = Server.MapPath(_directory) + "\\" + user.Pkid + fileExt; 35 Request.Files[0].SaveAs(fileName); 36 Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert(‘上传成功‘);</script>"); 37 Answer answer = (Answer)Session["Answer"]; 38 answer.Answer35 = "done"; 39 } 40 } 41 } 42 catch 43 { 44 throw new Exception(); 45 } 46 }
需要引入 using System.IO;
2. 下载文件前台页面
1 <asp:LinkButton runat="server" ID="DownLoadQuestionnaire" Text="下载文件" OnClick="DownLoadQuestionnaire_Click" />
下载文件后台代码
1 protected void DownLoadQuestionnaire_Click(object sender, EventArgs e) 2 { 3 Response.ContentType = "application/x-zip-compressed"; 4 5 string docName = "中高职衔接院校调研问卷.docx"; //文件路径 6 docName = HttpUtility.UrlEncode(docName, System.Text.Encoding.UTF8); 7 Response.AddHeader("Content-Disposition", "attachment;filename=" + docName); 8 string filename = Server.MapPath("DownLoad/中高职衔接院校调研问卷.docx"); 9 //指定编码 防止中文文件名乱码 10 Response.HeaderEncoding = System.Text.Encoding.GetEncoding("GB2312"); 11 Response.TransmitFile(filename); 12 13 }
值得注意的就是文件名设置一下编码,不然出现下载时文件名乱码:
HttpUtility.UrlEncode(docName, System.Text.Encoding.UTF8);
据说还有很多种下载方式,没一个一个的试验:
1 protected void DownLoadQuestionnaire_Click(object sender, EventArgs e) 2 { 3 string fileName = "asd.txt";//客户端保存的文件名 4 string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 5 6 FileInfo fileInfo = new FileInfo(filePath); 7 Response.Clear(); 8 Response.ClearContent(); 9 Response.ClearHeaders(); 10 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); 11 Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 12 Response.AddHeader("Content-Transfer-Encoding", "binary"); 13 Response.ContentType = "application/octet-stream"; 14 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 15 Response.WriteFile(fileInfo.FullName); 16 Response.Flush(); 17 Response.End(); 18 19 } 20 21 protected void DownLoadQuestionnaire_Click(object sender, EventArgs e) 22 { 23 string fileName = "aaa.txt";//客户端保存的文件名 24 string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 25 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); 26 if (fileInfo.Exists == true) 27 { 28 const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 29 byte[] buffer = new byte[ChunkSize]; 30 31 Response.Clear(); 32 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); 33 long dataLengthToRead = iStream.Length;//获取下载的文件总大小 34 Response.ContentType = "application/octet-stream"; 35 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); 36 while (dataLengthToRead > 0 && Response.IsClientConnected) 37 { 38 int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 39 Response.OutputStream.Write(buffer, 0, lengthRead); 40 Response.Flush(); 41 dataLengthToRead = dataLengthToRead - lengthRead; 42 } 43 Response.Close(); 44 } 45 } 46 47 protected void DownLoadQuestionnaire_Click(object sender, EventArgs e) 48 { 49 string fileName = "aaa.txt";//客户端保存的文件名 50 string filePath = Server.MapPath("DownLoad/aaa.txt");//路径 51 52 //以字符流的形式下载文件 53 FileStream fs = new FileStream(filePath, FileMode.Open); 54 byte[] bytes = new byte[(int)fs.Length]; 55 fs.Read(bytes, 0, bytes.Length); 56 fs.Close(); 57 Response.ContentType = "application/octet-stream"; 58 //通知浏览器下载文件而不是打开 59 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); 60 Response.BinaryWrite(bytes); 61 Response.Flush(); 62 Response.End(); 63 }
以上是关于C# ASP 上传/下载文件的主要内容,如果未能解决你的问题,请参考以下文章
C#使用HTML文件中的file文件上传,用C#代码接收上传文件