方式一:
/// <summary>
/// 文件下载类
/// 调用1:DownLoadFile("/2003.xls", null);
/// 调用2:DownLoadFile("/2003.xls", "");
/// 调用3:DownLoadFile("/2003.xls", "temp.xls");
/// </summary>
/// <param name="filePath">文件路径(格式:/upload/2003.xls)</param>
/// <param name="filename">自定义文件名(不想自定义文件名请传[ "" or null ] )</param>
public ActionResult DownFile(string filePath, string fileName)
- {
- filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
- FileStream fs = new FileStream(filePath, FileMode.Open);
- byte[] bytes = new byte[(int)fs.Length]; //以字符流的形式下载文件
- fs.Read(bytes, 0, bytes.Length);
- fs.Close();
- 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(bytes);
- Response.Flush();
- Response.End();
- return new EmptyResult();
- }
public FileStreamResult DownFile(string filePath, string fileName)
{
string absoluFilePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
return File(new FileStream(absoluFilePath, FileMode.Open), "application/octet-stream", Server.UrlEncode(fileName));
}
调用方式:
<a href="/Document/DownFile?filePath=@item.Value&fileName=@item.Key">下载</a>