1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > ASP.NET MVC自定义ActionResult实现文件压缩

ASP.NET MVC自定义ActionResult实现文件压缩

时间:2019-09-03 14:37:54

相关推荐

ASP.NET MVC自定义ActionResult实现文件压缩

有时候需要将单个或多个文件进行压缩打包后在进行下载,这里我自定义了一个ActionResult,方便进行文件下载

using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Web;using System.Web.Mvc;using WebSeat.Site.Member.Helper;namespace WebSeat.Site.Member.CustomResult{/// <summary>/// 说明:压缩文件/// 创建日期:/12/14 16:18:22/// 创建人:曹永承/// </summary>public class ZipResult : ActionResult{#region 字段private Ionic.Zip.ZipFile zip;#endregion#region 属性/// <summary>/// 文档类型/// </summary>public string ContentType{get;set;}/// <summary>/// 下载文件名称/// </summary>public string DownloadName { get; set; }#endregion#region 构造函数public ZipResult(string downLoadName =null){ContentType = "application/x-zip-compressed";DownloadName = downLoadName;zip = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8);}public ZipResult(params string[] filenames):this(){foreach (string filename in filenames){zip.AddFile(filename);}}public ZipResult(IDictionary<string,Stream> dir, string downLoadName = " ") : this(downLoadName){foreach (string key in dir.Keys){zip.AddEntry(key, dir[key]);}}#endregion#region 公共方法/// <summary>/// 添加文件/// </summary>/// <param name="filename"></param>public void AddFile(string filename){zip.AddFile(filename);}/// <summary>/// 添加流/// </summary>/// <param name="entryName"></param>/// <param name="stream"></param>public void AddEntry(string entryName, Stream stream){zip.AddEntry(entryName, stream);}/// <summary>/// 获取压缩后的流/// </summary>/// <returns></returns>public Stream GetStream(){Stream stream = new MemoryStream();zip.Save(stream);return stream;}#endregion#region 实现ExecuteResult方法public override void ExecuteResult(ControllerContext context){context.HttpContext.Response.ContentType = ContentType;string filename = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")+".zip";filename = DownloadName == null ? filename : DownloadName;//对文件名称进行编码,避免下载文件名称出现乱码filename = filename.EncodingDownloadFileName(); context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);Stream ms = GetStream();context.HttpContext.Response.AddHeader("Content-Length", ms.Length.ToString());ms.Seek(0, SeekOrigin.Begin);byte[] bytes = new byte[1024 * 10];int readSize = 0;var output = context.HttpContext.Response.OutputStream;while ((readSize = ms.Read(bytes, 0, bytes.Length)) > 0){output.Write(bytes, 0, readSize);context.HttpContext.Response.Flush();}}#endregion}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。