2014-03-12 85 views
0

我想將zip文件保存到服務器,但僅限於多個文件。 首先應該創建壓縮文件,然後上傳到文件夾爲多個文件創建zip文件,然後將其上傳到文件夾

if (FileUpload1.HasFile) 
    { 

     string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 
     string fileLocation = Server.MapPath("~/uploads/" + fileName); 

     FileUpload1.SaveAs(fileLocation); 



     ZipFile createZipFile = new ZipFile(); 

     createZipFile.AddFile(fileLocation, string.Empty); 

     createZipFile.Save(Server.MapPath("~/uploads/CsharpAspNetArticles.zip")); 

    } 
+1

和你的問題是什麼? – Jodrell

+0

https://www.nuget.org/packages/DotNetZip/ – Jodrell

+0

嗨...我的問題是,如果有多個文件,然後先創建zip文件,然後上傳該zip文件文件夾上傳按鈕點擊 – user3410018

回答

0

如果我明白你的「noquestion」的問題:)你應該使用的IHttpHandler這樣的:

using System; 
using System.IO; 
using System.Web; 
using ICSharpCode.SharpZipLib.Zip; 

public class ZipHandler : IHttpHandler 
{ 
    public bool IsReusable 
    { 
     get { return true; } 
    } 

    public void ProcessRequest(HttpContext ctx) 
    { 
     var path = HttpUtility.UrlDecode(ctx.Request.QueryString["folder"]); 
     if (path == null) 
     { 
      return; 
     } 
     var folderName = Path.GetFileName(path); 
     if (folderName == String.Empty) 
     { 
      folderName = "root"; 
     } 

     int folderOffset = ctx.Server.MapPath("~").Length; 

     using (var zipStream = new ZipOutputStream(ctx.Response.OutputStream)) 
     { 
      ctx.Response.Clear(); 
      ctx.Response.BufferOutput = false; 
      ctx.Response.AddHeader("Content-Disposition", "attachment; filename=" + folderName + ".zip"); 
      ctx.Response.AddHeader("Content-Type", "application/zip"); 

      zipStream.SetLevel(3); 

      CompressFolder(path, zipStream, folderOffset); 

      ctx.Response.Flush(); 
     } 
    } 

    private static void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) 
    { 
     string[] files = Directory.GetFiles(path); 
     foreach (string filename in files) 
     { 
      try 
      { 
       using (var streamReader = File.OpenRead(filename)) 
       { 
        var fi = new FileInfo(filename); 

        string entryName = filename.Substring(folderOffset); 
        entryName = ZipEntry.CleanName(entryName); 

        var newEntry = new ZipEntry(entryName) 
        { 
         DateTime = fi.LastWriteTime, 
         Size = fi.Length 
        }; 

        zipStream.PutNextEntry(newEntry); 

        streamReader.CopyTo(zipStream, 4096); 

        zipStream.CloseEntry(); 
       } 
      } 
      catch (IOException) { } 
     } 

     var folders = Directory.GetDirectories(path); 
     foreach (string folder in folders) 
     { 
      CompressFolder(folder, zipStream, folderOffset); 
     } 
    } 
} 
相關問題