using System;
using System.IO;
using System.Text;
using System.Web;
/// <summary>
/// 文件下载
/// </summary>
namespace Download.Service
{
/// <summary>
/// PDF文件下载帮助类
/// </summary>
public class DownloadFile
{
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileName">用户下载时看到的文件名</param>
/// <param name="filePath">文件路径</param>
public void Download(string fileName, string filePath)
{
byte[] buffer = ReaderFile(filePath);
Download(fileName, buffer);
}
/// <summary>
/// 下载
/// </summary>
/// <param name="fileName">用户下载时看到的文件名</param>
/// <param name="fileBuffer">文件的二进制流</param>
/// <param name="contentType">下载的文件ContentType</param>
public void Download(string fileName, byte[] fileBuffer, string contentType = "application/pdf")
{
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(fileName, Encoding.UTF8));
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.BinaryWrite(fileBuffer);
HttpContext.Current.Response.End();
}
/// <summary>
/// 将文件读取为二进制流
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public byte[] ReaderFile(string filePath)
{
try
{
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
return buffer;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
这是进行文件下载的方法,调用该方法,即可实现文件下载。
注意:这里是下载pdf文件(string contentType = "application/pdf"),要是其他格式文件,改变contentType 即可。