zipuploadstreamprovider.cs

来自「大文件上传组件」· CS 代码 · 共 94 行

CS
94
字号
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using ICSharpCode.SharpZipLib.Zip;

using Krystalware.SlickUpload;
using Krystalware.SlickUpload.Providers;

/// <summary>
/// An <see cref="IUploadStreamProvider" /> that streams each file into its own .zip file.
/// </summary>
public class ZipUploadStreamProvider : IUploadStreamProvider
{
    public Stream GetInputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipInputStream zipS = null;

        try
        {
            string path = GetZipPath(file);

            fileS = File.OpenRead(path);
            zipS = new ZipInputStream(fileS);

            zipS.GetNextEntry();

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }

    public Stream GetOutputStream(UploadedFile file)
    {
        FileStream fileS = null;
        ZipOutputStream zipS = null;

        try
        {
            string outputPath = GetZipPath(file);

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            fileS = File.OpenWrite(outputPath);
            zipS = new ZipOutputStream(fileS);

            zipS.SetLevel(5);

            zipS.PutNextEntry(new ZipEntry(file.ClientName));

            return zipS;
        }
        catch
        {
            if (fileS != null)
                fileS.Dispose();

            if (zipS != null)
                zipS.Dispose();

            return null;
        }
    }

    public void RemoveOutput(UploadedFile file)
    {
        string path = GetZipPath(file);

        if (File.Exists(path))
            File.Delete(path);
    }

    string GetZipPath(UploadedFile file)
    {
        return Path.Combine(HttpContext.Current.Server.MapPath("~/Files/"), Path.GetFileNameWithoutExtension(file.ClientName) + ".zip");
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?