欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用ASP.Net实现文件的在线压缩和解压缩

程序员文章站 2023-01-10 08:16:42
  我们经常会遇到批量上传的问题,也会遇到将某个目录下所有文件都上传到服务器上的问题。那么,如何解决此类问题呢?以前的技术一般采用activex等方式,这里笔者采用shar...

  我们经常会遇到批量上传的问题,也会遇到将某个目录下所有文件都上传到服务器上的问题。那么,如何解决此类问题呢?以前的技术一般采用activex等方式,这里笔者采用sharpzlib来实现,听说vs2005已有压缩和解压缩的解决方案,笔者还没有时间用vs2005,所以就只好使用vs2003 + sharpzlib来解决问题了。

  1、首先从这里下载0.84版本的sharpzlib源码及示例码。
  2、下载下来之后你发现它没有vs2003的解决方案文件,没有关系。你可以自己建立,首先新建一个zipunzip的解决方案,然后,将上面经过解压缩之后的所有文件及目录copy到你的解决方案所在的目录下。
  3、在vs2003解决方案资源管理器(一般是在右上方中部点的位置)中点击显示所有文件按钮,然后可以见到很多“虚”的图标、文件及文件夹等,可以一次选择它们,然后包含进项目中。
  4、编译,最好使用release选项,编译完成之后你可以在\bin\release\看到zipunzip.dll的类了。如果你编译时报错,说什么assemblykeyfile之类的,你可以使用强命名工具新建一个,也可以将assemblyinfo.cs中[assembly: assemblykeyfile("。。。。。")]改成:[assembly: assemblykeyfile("")]  (不推荐这样做)。
  5、新建一个webform项目,添加zipunzip.dll类的引用,然后添加如下文件及内容:

// ------------------------------------------
// 1. attachmentunzip.cs
// ------------------------------------------
using system;
using system.io;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.gzip;
using icsharpcode.sharpziplib.bzip2;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip.compression;
using icsharpcode.sharpziplib.zip.compression.streams;

namespace webzipunzip
{
 public class attachmentunzip
 {
  public attachmentunzip()
  {  
  }
  public static void upzip(string zipfile)
  {
   string []fileproperties=new string[2];
   fileproperties[0]=zipfile;//待解压的文件
   fileproperties[1]=zipfile.substring(0,zipfile.lastindexof("\\")+1);//解压后放置的目标目录
   unzipclass unzc=new unzipclass();
   unzc.unzip(fileproperties);
  }
 }
}

// ---------------------------------------------
// 2. unzipclass.cs
// ---------------------------------------------

using system;
using system.io;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.gzip;
using icsharpcode.sharpziplib.bzip2;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip.compression;
using icsharpcode.sharpziplib.zip.compression.streams;

namespace webzipunzip
{
 public class unzipclass
 {  
  /// <summary>
  /// 解压文件
  /// </summary>
  /// <param name="args">包含要解压的文件名和要解压到的目录名数组</param>
  public void unzip(string[] args)
  {
   zipinputstream s = new zipinputstream(file.openread(args[0]));
   try
   {   
    zipentry theentry;
    while ((theentry = s.getnextentry()) != null)
    {  
     string directoryname = path.getdirectoryname(args[1]);
     string filename      = path.getfilename(theentry.name);

     //生成解压目录
     directory.createdirectory(directoryname);

     if (filename != string.empty)
     {  
      //解压文件到指定的目录
      filestream streamwriter = file.create(args[1]+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();
   }

  }//end unzip

  public static bool unzipfile(string file, string dir)
  {
   try
   {
    if (!directory.exists(dir))
     directory.createdirectory(dir);
    string filefullname = path.combine(dir,file);
    zipinputstream s = new zipinputstream(file.openread( filefullname ));

    zipentry theentry;
    while ((theentry = s.getnextentry()) != null)
    {
     string directoryname = path.getdirectoryname(theentry.name);
     string filename = path.getfilename(theentry.name);

     if (directoryname != string.empty)
      directory.createdirectory( path.combine(dir, directoryname));

     if (filename != string.empty)
     {
      filestream streamwriter = file.create( path.combine(dir,theentry.name) );
      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();
    return true;
   }
   catch (exception)
   {
    throw;
   }
  }

 }//end unzipclass
}

// ----------------------------------------------
// 3. zipclass.cs
// ----------------------------------------------
using system;
using system.io;
using icsharpcode.sharpziplib.zip;
using icsharpcode.sharpziplib.gzip;
using icsharpcode.sharpziplib.bzip2;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip.compression;
using icsharpcode.sharpziplib.zip.compression.streams;

namespace webzipunzip
{
 /// <summary>
 /// 压缩文件
 /// </summary>
 public class zipclass
 {
  public void zipfile(string filetozip, string zipedfile ,int compressionlevel, int blocksize,string password)
  {
   //如果文件没有找到,则报错
   if (! system.io.file.exists(filetozip))
   {
    throw new system.io.filenotfoundexception("the specified file " + filetozip + " could not be found. zipping aborderd");
   }

   system.io.filestream streamtozip = new system.io.filestream(filetozip,system.io.filemode.open , system.io.fileaccess.read);
   system.io.filestream zipfile = system.io.file.create(zipedfile);
   zipoutputstream zipstream = new zipoutputstream(zipfile);
   zipentry zipentry = new zipentry("zippedfile");
   zipstream.putnextentry(zipentry);
   zipstream.setlevel(compressionlevel);
   byte[] buffer = new byte[blocksize];
   system.int32 size =streamtozip.read(buffer,0,buffer.length);
   zipstream.write(buffer,0,size);
   try
   {
    while (size < streamtozip.length)
    {
     int sizeread =streamtozip.read(buffer,0,buffer.length);
     zipstream.write(buffer,0,sizeread);
     size += sizeread;
    }
   }
   catch(system.exception ex)
   {
    throw ex;
   }
   zipstream.finish();
   zipstream.close();
   streamtozip.close();
  }

  public void zipfilemain(string[] args)
  {
   //string[] filenames = directory.getfiles(args[0]);
   string[] filenames = new string[]{args[0]};

   crc32 crc = new crc32();
   zipoutputstream s = new zipoutputstream(file.create(args[1]));

   s.setlevel(6); // 0 - store only to 9 - means best compression

   foreach (string file in filenames)
   {
    //打开压缩文件
    filestream fs = file.openread(file);  
    byte[] buffer = new byte[fs.length];
    fs.read(buffer, 0, buffer.length);
    zipentry entry = new zipentry(file);

    entry.datetime = datetime.now;

    // set size and the crc, because the information
    // about the size and crc should be stored in the header
    // if it is not set it is automatically written in the footer.
    // (in this case size == crc == -1 in the header)
    // some zip programs have problems with zip files that don't store
    // the size and crc in the header.
    entry.size = fs.length;
    fs.close();

    crc.reset();
    crc.update(buffer);

    entry.crc  = crc.value;

    s.putnextentry(entry);

    s.write(buffer, 0, buffer.length);

   } 
   s.finish();
   s.close();
  }
 }
}

// ---------------------------------------------
// 4. webform1.aspx
// ---------------------------------------------
  <%@ page language="c#" codebehind="webform1.aspx.cs" autoeventwireup="false" inherits="webzipunzip.webform1" %> 
<meta content="microsoft visual studio .net 7.1" name=generator>
<meta content=c# name=code_language>
<meta content=javascript name=vs_defaultclientscript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetschema>
<form id=form1 method=post runat="server"><?xml:namespace prefix = asp /><asp:button id=button1 style="z-index: 101; left: 56px; position: absolute; top: 64px" runat="server" text="压缩"></asp:button><asp:button id=button2 style="z-index: 102; left: 112px; position: absolute; top: 64px" runat="server" text="解压"></asp:button><input id=file1 style="z-index: 103; left: 32px; position: absolute; top: 24px" type=file name=file1 runat="server"> </form></body></html>

//-------------------------------------------
// 5.webform1.aspx.cs
//-------------------------------------------

using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.io;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;

namespace webzipunzip
{
 /// <summary>
 /// summary description for webform1.
 /// </summary>
 public class webform1 : system.web.ui.page
 {
  protected system.web.ui.webcontrols.button button1;
  protected system.web.ui.htmlcontrols.htmlinputfile file1;
  protected system.web.ui.webcontrols.button button2;

  private void page_load(object sender, system.eventargs e)
  {
   // put user code to initialize the page here
  }

  #region web form designer generated code
  override protected void oninit(eventargs e)
  {
   //
   // codegen: this call is required by the asp.net web form designer.
   //
   initializecomponent();
   base.oninit(e);
  }

  /// <summary>
  /// required method for designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void initializecomponent()
  {   
   this.button1.click += new system.eventhandler(this.button1_click);
   this.button2.click += new system.eventhandler(this.button2_click);
   this.load += new system.eventhandler(this.page_load);

  }
  #endregion

  #region 压缩
  private void button1_click(object sender, system.eventargs e)
  {
   string []fileproperties=new string[2];  
   string fullname=this.file1.postedfile.filename;//c:\test\a.txt
   string destpath=system.io.path.getdirectoryname(fullname);//c:\test
   //待压缩文件
   fileproperties[0]=fullname;

   //压缩后的目标文件
   fileproperties[1]= destpath +"\\"+ system.io.path.getfilenamewithoutextension(fullname) + ".zip";
   zipclass zc=new zipclass();
   zc.zipfilemain(fileproperties);

   //删除压缩前的文件
   system.io.file.delete(fullname);
  }

  #endregion

  #region 解压
  private void button2_click(object sender, system.eventargs e)
  {
   string fullname=this.file1.postedfile.filename;//c:\test\a.zip
   //解压文件
   //attachmentunzip.upzip(fullname);

//   string[] fileproperties = new string[2];
//   fileproperties[0] = fullname;//待解压的文件
//   fileproperties[1] = system.io.path.getdirectoryname(fullname);//解压后放置的目标目录
//   unzipclass unzc=new unzipclass();
//   unzc.unzip(fileproperties);
   string dir = system.io.path.getdirectoryname(fullname);
   string filename = system.io.path.getfilename(fullname);
   unzipclass.unzipfile(filename, dir);
  }
  #endregion
 }
}

  ok! 试试看。

  此方案解决了文件名中文字的问题,目录解压缩问题。
  至于整个文件夹批量上传并压缩成一个winzip压缩包的问题,没有时间解决了,各位如有解决方案,不妨共享一下。