asp.net upload large files

ASP.NET upload files FileUpLoad can, but the operation of the folder can not use FileUpLoad to achieve.

The following example is to use ASP.NET to upload folders and folder compression and decompression.

ASP.NET page design: TextBox and a Button.

TextBox in need themselves to be input path to the folder (containing folder), select the folder implementation issues have not been resolved by Button, can only temporarily be entered manually.

Two kinds of methods: rar and zip.

1. Generate rar

using Microsoft.Win32;

using System.Diagnostics;

protected void Button1Click(object sender, EventArgs e)

    {

        RAR(@"E:\95413594531\GIS", "tmptest", @"E:\95413594531\");

    }

    ///

   /// Compressed file

   ///

   /// need to compress individual files or folders

   /// generate compressed file name

   /// generate a compressed file path

   ///

    protected bool RAR(string DFilePath, string DRARName,string DRARPath)

    {

        String therar;

        RegistryKey theReg;

        Object theObj;

        String theInfo;

        ProcessStartInfo theStartInfo;

        Process theProcess;

        try

        {

            theReg = Registry.ClassesRoot.OpenSubKey (@ "Applications \ WinRAR.exe \ Shell \ Open \ Command"); // Note: This path was not found in the root registry path

            theObj = theReg.GetValue("");

            therar = theObj.ToString();

            theReg.Close();

            therar = therar.Substring(1, therar.Length - 7);

            theInfo = "a" + "" + DRARName + "" + DFilePath + "-ep1"; // + command + file name or the path of the compressed file compressed

            theStartInfo = new ProcessStartInfo();

            theStartInfo.FileName = therar;

            theStartInfo.Arguments = theInfo;

            theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            theStartInfo.WorkingDirectory = DRARPath; // RaR file storage directory.

            theProcess = new Process();

            theProcess.StartInfo = theStartInfo;

            theProcess.Start();

            theProcess.WaitForExit();

            theProcess.Close();

            return true;

        }

        catch (Exception ex)

        {

            return false;

        }

    }

 

    ///

    /// unzips to the specified folder

    ///

    /// directory exists a file compression

    /// compressed file name

    /// unzip to a folder

    ///

    protected bool UnRAR(string RARFilePath,string RARFileName,string UnRARFilePath)

    {

        //unzip

        String therar;

        RegistryKey theReg;

        Object theObj;

        String theInfo;

        ProcessStartInfo theStartInfo;

        Process theProcess;

        try

         {

            theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");

            theObj = theReg.GetValue("");

            therar = theObj.ToString();

            theReg.Close();

            therar = therar.Substring(1, therar.Length - 7);

            theInfo = @" X " + " " + RARFilePath + RARFileName + " " + UnRARFilePath;

            theStartInfo = new ProcessStartInfo();

            theStartInfo.FileName = therar;

            theStartInfo.Arguments = theInfo;

            theStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            theProcess = new Process();

            theProcess.StartInfo = theStartInfo;

            theProcess.Start();

            return true;

        }

        catch (Exception ex)

         {

             return false;

         }

    }

Note: This method should be in the path was not found in the computer registry is not implemented, for reference purposes only.

2. Generate zip

By calling the library ICSharpCode.SharpZipLib.dll

The library can be downloaded from the Internet. It can be downloaded from this link: SharpZipLib_0860_Bin.zip

Add two classes: Zip.cs and UnZip.cs

(1)Zip.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

using System.IO;

using System.Collections;

using ICSharpCode.SharpZipLib.Checksums;

using ICSharpCode.SharpZipLib.Zip;

 

 

namespace UpLoad

{

    /// <summary>

    /// function: archive

    /// creator chaodongwang 2009-11-11

    /// </summary>

    public class Zip

    {

        /// <summary>

        /// compress a single file

        /// </summary>

        /// <param name = "FileToZip"> compressed file name (including the file path) </ param>

        /// file name after <param name = "ZipedFile"> Compression (including file path) </ param>

        /// <param name = "CompressionLevel"> Compression ratio 0 (no compression) to 9 (highest compression rate) </ param>

        /// <param name = "BlockSize"> Cache Size </ param>

        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)

        {

            // If the file is not found, an error

            if (!System.IO.File.Exists(FileToZip))

            {

                throw new System.IO.FileNotFoundException ( "file:" + FileToZip + "not found!");

            }

 

            if (ZipedFile == string.Empty)

            {

                ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";

            }

 

            if (Path.GetExtension(ZipedFile) != ".zip")

            {

                ZipedFile = ZipedFile + ".zip";

            }

 

            //// If you specify a directory location does not exist, create it

            //string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("\\"));

            //if (!Directory.Exists(zipedDir))

            //    Directory.CreateDirectory(zipedDir);

 

            // compressed file name

            string filename = FileToZip.Substring(FileToZip.LastIndexOf('\\') + 1);

           

            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(filename);

            ZipStream.PutNextEntry(ZipEntry);

            ZipStream.SetLevel(CompressionLevel);

            byte[] buffer = new byte[2048];

            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;

            }

            finally

            {

                ZipStream.Finish();

                ZipStream.Close();

                StreamToZip.Close();

            }

        }

 

        /// <summary>

        /// folder compression method

        /// </summary>

        public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)

        {

            // default compressed file is empty and compressed folders at the same level directory

            if (ZipedFile == string.Empty)

            {

                ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("\\") + 1);

                ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("\\")) +"\\"+ ZipedFile+".zip";

            }

 

            if (Path.GetExtension(ZipedFile) != ".zip")

            {

                ZipedFile = ZipedFile + ".zip";

            }

 

            using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))

            {

                zipoutputstream.SetLevel(CompressionLevel);

                Crc32 crc = new Crc32();

                Hashtable fileList = getAllFies(DirToZip);

                foreach (DictionaryEntry item in fileList)

                {

                    FileStream fs = File.OpenRead(item.Key.ToString());

                    byte[] buffer = new byte[fs.Length];

                    fs.Read(buffer, 0, buffer.Length);

                    ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length + 1));

                    entry.DateTime = (DateTime)item.Value;

                    entry.Size = fs.Length;

                    fs.Close();

                    crc.Reset();

                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    zipoutputstream.PutNextEntry(entry);

                    zipoutputstream.Write(buffer, 0, buffer.Length);

                }

            }

        }

 

        /// <summary>

        /// Get all files

        /// </summary>

        /// <returns></returns>

        private Hashtable getAllFies(string dir)

        {

            Hashtable FilesList = new Hashtable();

            DirectoryInfo fileDire = new DirectoryInfo(dir);

            if (!fileDire.Exists)

            {

                throw new System.IO.FileNotFoundException ( "directory:" + fileDire.FullName + "not found!");

            }

 

            this.getAllDirFiles(fileDire, FilesList);

            this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);

            return FilesList;

        }

        /// <summary>

        /// get a folder of all the files in the folder

        /// </summary>

        /// <param name="dirs"></param>

        /// <param name="filesList"></param>

        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)

        {

            foreach (DirectoryInfo dir in dirs)

            {

                foreach (FileInfo file in dir.GetFiles("*.*"))

                {

                    filesList.Add(file.FullName, file.LastWriteTime);

                }

                this.getAllDirsFiles (dir.GetDirectories () files list);

            }

        }

        /// <summary>

        /// Gets a file folder

        /// </summary>

        /// <param name = "strDirName"> directory name </ param>

        /// <param name = "filesList"> File List HastTable </ param>

        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)

        {

            foreach (FileInfo file in dir.GetFiles("*.*"))

            {

                filesList.Add(file.FullName, file.LastWriteTime);

            }

        }

    }

}

(2)UnZip.cs

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

/// <summary>

/// unzip files

/// </summary>

 

using System;

using System.Text;

using System.Collections;

using System.IO;

using System.Diagnostics;

using System.Runtime.Serialization.Formatters.Binary;

using System.Data;

 

using ICSharpCode.SharpZipLib.Zip;

using ICSharpCode.SharpZipLib.Zip.Compression;

using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

 

namespace UpLoad

{

    /// <summary>

    /// function: Unzip the file

    /// creator chaodongwang 2009-11-11

    /// </summary>

    public class UnZipClass

    {

        /// <summary>

        /// function: Extract the zip file format.

        /// </summary>

        /// <param name = "zipFilePath"> archive path </ param>

        /// <param name = "unZipDir"> extracting file storage path is empty by default with the compressed file under the same parent directory, file with the same name as the compressed file folder </ param>

        /// <param name = "err"> error message </ param>

        /// <returns> decompression success </ returns>

        public void UnZip(string zipFilePath, string unZipDir)

        {

            if (zipFilePath == string.Empty)

            {

                throw new Exception ( "compressed files can not be empty!");

            }

            if (!File.Exists(zipFilePath))

            {

                throw new System.IO.FileNotFoundException ( "compressed file does not exist!");

            }

            The default compression file under the same parent directory, file with the same name as the compressed file folder when // extract the folder is empty

            if (unZipDir == string.Empty)

                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));

            if (!unZipDir.EndsWith("\\"))

                unZipDir += "\\";

            if (!Directory.Exists(unZipDir))

                Directory.CreateDirectory(unZipDir);

 

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))

            {

 

                ZipEntry theEntry;

                while ((theEntry = s.GetNextEntry()) != null)

                {

                    string directoryName = Path.GetDirectoryName(theEntry.Name);

                    string fileName = Path.GetFileName(theEntry.Name);

                    if (directoryName.Length > 0)

                    {

                        Directory.CreateDirectory(unZipDir + directoryName);

                    }

                    if (!directoryName.EndsWith("\\"))

                        directoryName += "\\";

                    if (fileName != String.Empty)

                    {

                        using (FileStream streamWriter = File.Create(unZipDir + 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;

                                }

                            }

                        }

                    }

                }

            }

        }

    }

}

Both can create more libraries directly in the program library, and then copy and paste, you can directly call.

Main code is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Drawing;

 

using Microsoft.Win32;

using System.Diagnostics;

 

 

namespace UpLoad

{

    public partial class UpLoadForm : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

            if (TextBox1.Text == "") // If the input is empty, the pop-up prompts

            {

                this.Response.Write ( "<script> alert ( 'input is empty. Please reenter!'); window.opener.location.href = window.opener.location.href; </ script>");

            }

            else

            {

                // Compressed Folders

                string zipPath = TextBox1.Text.Trim (); // Get the path to be compressed (including folders)

                string zipedPath = @ "c: \ temp"; // compression path to the folder (including folders)

                Zip Zc = new Zip();

                Zc.ZipDir (zipPath, zipedPath, 6);

                this.Response.Write("<script>alert('压缩成功!');window.opener.location.href=window.opener.location.href;</script>");

 

                // extract the folder

                UnZipClass unZip = new UnZipClass();

                unZip.UnZip (zipedPath + ".zip", @ "c: \ temp"); // To extract the path to the folder (including the file name) and extraction path (temp file folder is the input file path folder )

                this.Response.Write("<script>alert('解压成功!');window.opener.location.href=window.opener.location.href;</script>");

 

            }

        }

    }

}

This method has been tested, it has been achieved.

In addition, attach another file upload method, the test has been implemented, reference links: http://blog.ncmem.com/wordpress/2019/11/20/net%e4%b8%8a%e4%bc%a0 % e5% a4% a7% e6 % 96% 87% e4% bb% b6% e7% 9a% 84% e8% a7% a3% e5% 86% b3% e6% 96% b9% e6% a1% 88 / 

Welcome to the group to discuss: 374 992 201

 

Guess you like

Origin www.cnblogs.com/songsu/p/12582861.html