.NET下载,有文件源存在。
public static void DownLoadFile(string fileName, HttpResponse Response, HttpServerUtility Server) { string path = Server.MapPath("~/UpFiles/" + fileName); FileInfo fileInfo = new FileInfo(path); //TextWriter writer = new StreamWriter(defultPath); //HttpResponse Response = new HttpResponse(writer); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "attachment; filename="" + Server.UrlEncode(fileName) + """); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End(); }
以文本流的方式下载,不存在文件源的方式。
byte[] tmp = ProServer.XLSIO.ExportExcel(dt, salEnt.NAME);//二进制字符 string fileName = string.Format("{0}.xls", salEnt.NAME); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName)); Response.BinaryWrite(tmp); Response.Flush(); Response.End();
MVC下载,存在文件源
public FileStreamResult DownFile(string fileid) { using (DBEntities db = new DBEntities()) { int id = Convert.ToInt32(fileid); var files = db.PS_FILES.SingleOrDefault(k => k.ID == id); string path = Server.MapPath("~/UpFiles/") + files.PATH; return File(new FileStream(path, FileMode.Open), "image/jpeg jpeg jpg jpe", files.NAME); } }
MVC下载,以二进制字符串
public ActionResult DownF(string fileid) { using (DBEntities db = new DBEntities()) { int id = Convert.ToInt32(fileid); var files = db.PS_FILES.SingleOrDefault(k => k.ID == id); string path = Server.MapPath("~/UpFiles/") + files.PATH; FileInfo file=new FileInfo(path); byte[] buffer; using (FileStream fs = file.Open(FileMode.Open)) { buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); } Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(files.PATH)); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); } return View(); }