MVC中简单的文件下载代码
/// <summary> /// 文件下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> /// <returns></returns> public FileStreamResult DownLoadFile(string filePath,string fileName) { Stream stream = null; try { if (System.IO.File.Exists(filePath)) { stream = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (stream != null) { return File(stream, "application/octet-stream", Url.Encode(fileName)); } else { throw new Exception("文件不存在!"); } } else { throw new Exception("文件不存在!"); } } catch(Exception exc) { throw new Exception(""); } }
public void Download() { Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(Path.GetFileName(Server.UrlDecode(Request["filepath"])))); Response.WriteFile(Server.MapPath(Server.UrlDecode(Request["filepath"]))); Response.Flush(); Response.End(); }