asp.net 文件下载与压缩
1.添加ICSharpCode.SharpZipLib.dll(该组件是压缩组件)
2.添加一个压缩辅助类,可以压缩多个文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
namespace CSharpZipLibHelper
{
public class SharpZipLibHelper
{
// <summary>
/// 压缩指定文件生成ZIP文件
/// </summary>
/// <param name="topDirName">顶层文件夹名称 \Storage Card\PDADataExchange\send\xml\</param>
/// <param name="fileNamesToZip">待压缩文件列表 file名 ddd.txt</param>
/// <param name="ZipedFileName">ZIP文件 \Storage Card\PDADataExchange\send\zip\version.zip</param>
/// <param name="CompressionLevel">压缩比 7</param>
/// <param name="password">密码 ""</param>
/// <param name="comment">压缩文件注释文字 ""</param>
public static void ZipFile(string topDirName, string[] fileNamesToZip, string ZipedFileName, int CompressionLevel, string password, string comment)
{
using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Open(ZipedFileName, FileMode.Create)))
{
if (password != null && password.Length > 0)
s.Password = password;
if (comment != null && comment.Length > 0)
s.SetComment(comment);
s.SetLevel(CompressionLevel); // 0 - means store only to 9 - means best compression
foreach (string file in fileNamesToZip)
{
using (FileStream fs = File.OpenRead(Path.Combine(topDirName, file))) //打开待压缩文件
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length); //读取文件流
ZipEntry entry = new ZipEntry(file); //新建实例
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
s.Finish();
s.Close();
}
}
/// <summary>
/// 解压缩ZIP文件到指定文件夹
/// </summary>
/// <param name="zipfileName">ZIP文件</param>
/// <param name="UnZipDir">解压文件夹</param>
/// <param name="password">压缩文件密码</param>
public static void UnZipFile(string zipfileName, string UnZipDir, string password)
{
//zipfileName=@"\Storage Card\PDADataExchange\receive\zip\test.zip";
//UnZipDir= @"\Storage Card\PDADataExchange\receive\xml\";
//password="";
ZipInputStream s = new ZipInputStream(File.OpenRead(zipfileName));
if (password != null && password.Length > 0)
s.Password = password;
try
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(UnZipDir);
string pathname = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
pathname = pathname.Replace(":", "$");//处理压缩时带有盘符的问题
directoryName = directoryName + "\\" + pathname;
Directory.CreateDirectory(directoryName);
if (fileName != String.Empty)
{
//解压文件到指定的目录
FileStream streamWriter = File.Create(directoryName + "\\" + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
}
catch (Exception eu)
{
throw eu;
}
finally
{
s.Close();
}
}
}
}
页面前台代码
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
var sFeatures = "dialogHeight:50px;dialogWidth:1200px;center:yes;scroll:yes;status:no;";
function modopen() {
window.showModalDialog("/Page/hp.aspx", this, sFeatures);
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBox1" Text="100000" runat="server"></asp:TextBox>
<div>
<asp:Label ID="Label1" runat="server" Text="0" EnableViewState="false"></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text="0"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="生成txt" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="分割txt" />
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="下载zip" />
<input id="Button2" type="button" value="自适应" onclick='modopen();' />
</div>
</asp:Content>
我这里用了模板页,需要的人就拿那个几个button控件与文本就可以
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using CSharpZipLibHelper;
public partial class _Default : System.Web.UI.Page
{
string path;
int identity;
string rootPath;
protected void Page_Load(object sender, EventArgs e)
{
path = Server.MapPath("/File/File.txt");
rootPath = Server.MapPath("/File/DownLoad/");
identity = 45000;
}
protected void Button1_Click(object sender, EventArgs e)
{
// Label1.Text = (Int32.Parse(Label1.Text) + 1).ToString();
//Label2.Text = (Int32.Parse(Label2.Text) + 1).ToString();
Thread t = new Thread(() => { WriteFile(); });
t.Start();
// Response.Write("<script>alert(1)</script>");
}
protected void WriteFile()
{
int count = int.Parse(TextBox1.Text.Trim());
FileStream fs = File.Open(path, FileMode.Create, FileAccess.ReadWrite);
string s = DateTime.Now.ToString("yyyyMMddHHmmss");
using (StreamWriter sw = new StreamWriter(fs))
{
for (int i = 1; i <= count; i++)
{
sw.WriteLine(i + ": " + s + i.ToString());
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (!Directory.Exists(rootPath))
{
Directory.CreateDirectory(rootPath);
}
Thread t = new Thread(() =>
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
using (fs)
{
StreamReader sr = new StreamReader(fs);
StringBuilder sb = new StringBuilder();
List<string> FileNames = new List<string>();
string rootPathDate = rootPath + DateTime.Now.Year.ToString() + "\\";
if (!Directory.Exists(rootPathDate))
{
Directory.CreateDirectory(rootPathDate);
}
string line = sr.ReadLine();
int i = 1;
int j = 0;
while (line != null && j < i * identity)
{
sb.AppendLine(line);
line = sr.ReadLine();
j++;
if (line == null || (line != null && j == i * identity))
{
FileNames.Add(WriteFile(rootPathDate, sb.ToString()));
sb = sb.Clear();
i++;
}
}
if (FileNames.Count > 0)
{
Compress(rootPathDate, FileNames);
}
}
});
t.Start();
}
/// <summary>
/// 写文件
/// </summary>
protected string WriteFile(string RootPath, string FileTxt)
{
string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
string FilePath = Path.Combine(RootPath, FileName);
using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fs);
using (sw)
{
sw.Write(FileTxt);
}
}
return FileName;
}
public string Compress(string RootPath, List<string> filename)
{
// 压缩
string Name = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
string FileName = Path.Combine(RootPath, Name);
string topPath = Path.GetPathRoot(RootPath);
SharpZipLibHelper.ZipFile(RootPath, filename.ToArray(), FileName, 7, "", "");
return FileName;
}
protected void Button4_Click(object sender, EventArgs e)
{
Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, "20101212225148156.zip", @"/File/DownLoad/2010/", 1024000);
if (!success)
Response.Write("下载文件出错!");
Page.Response.End();
}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(HttpContext.Current.Server.MapPath(Path.Combine(_fullPath, _fileName)), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
double pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
//Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
}
后台代码。
直接copy去用就可以
posted on 2010-12-13 09:14 jianshaohui 阅读(1134) 评论(4) 编辑 收藏 举报