WinForm Program compressed file upload, server-side ASP-NET MVC to receive decompression

Source: Internet
Author: User
Tags crc32

There is no difficulty in programming, the only possible way to ignore the resulting failure is the ASP.

For large compressed files, you need to configure the maximum amount of MVC to receive:

  <system.web>    

  

Compress and upload in WinForm:

The invocation section is as follows:

String Propath = Application.startuppath + "\\temp\\product\\" + project. ProjectName; ZipFile (Propath,propath + ". zip");//compression var uploadresult = upload_request (Webconfig.uploadurl + "/mobile/ Receiveprojectfile ", Propath +". Zip ", project. ProjectName + ". zip");//upload if (Uploadresult = = 0) {loadingform.closeloadingcircle (); Notification t = new Notification ("scheme attachment upload failed, please try again!") ", 3, FormAnimator.AnimationMethod.Slide, FormAnimator.AnimationDirection.Up, True," error "); T.show (); return;} File.delete (Propath + ". zip");

 

<summary>///ZIP file///</summary>//<param name= "strfile" > File path to be compressed &LT;/PARAM&G        T            <param name= "Strzip" > Compressed file path </param> public void ZipFile (String strfile, String strzip) { if (strfile[strfile.length-1]! = Path.directoryseparatorchar) strfile + = Path.directoryseparatorc            Har            Zipoutputstream s = new Zipoutputstream (File.create (strzip)); S.setlevel (6);            0-store 9-means Best compression zip (strfile, S, strfile);            S.finish ();        S.close (); } private void Zip (String strfile, Zipoutputstream s, string staticfile) {if (strfile[strfile.le            NGTH-1]! = Path.directoryseparatorchar) strfile + = Path.directoryseparatorchar;            Crc32 CRC = New Crc32 ();            string[] filenames = directory.getfilesystementries (strfile);            foreach (string file in filenames) {    if (directory.exists (file)) {Zip (file, S, staticfile); } else//otherwise directly compress file {//Open compressed file FileStream fs = File.ope                    Nread (file); byte[] buffer = new BYTE[FS.                    Length]; Fs. Read (buffer, 0, buffer.                    Length); String tempfile = file.                    Substring (staticfile.lastindexof ("\ \") + 1);                    ZipEntry entry = new ZipEntry (tempfile); Entry.                    DateTime = DateTime.Now; Entry. Size = fs.                    Length; Fs.                    Close (); Crc.                    Reset (); Crc.                    Update (buffer); Entry. CRC = CRC.                    Value;                    S.putnextentry (entry); S.write (buffer, 0, buffer.)                Length); }            }        }

<summary>///upload local files to the specified server (HttpWebRequest method)///</summary>//<param name= "add Ress "> Files uploaded to the server </param>//<param name=" Filenamepath "> Local files to be uploaded (full path) </param>//<pa Ram Name= "Savename" > file name after upload </param>//<returns> Successful return 1, failed to return 0</returns> private int UPL            Oad_request (string address, String Filenamepath, String savename) {int returnvalue = 0;            File to upload FileStream fs = new FileStream (Filenamepath, FileMode.Open, FileAccess.Read);            BinaryReader r = new BinaryReader (FS);            Timestamp string strboundary = "----------" + DateTime.Now.Ticks.ToString ("x");            byte[] Boundarybytes = Encoding.ASCII.GetBytes ("\r\n--" + strboundary + "\ r \ n");            Request header information StringBuilder SB = new StringBuilder (); Sb.            Append ("--"); Sb.            Append (strboundary); Sb.            Append ("\ r \ n"); Sb. Append ("Content-disposition:form-data;            Name= ' "); Sb.            Append ("file"); Sb. Append ("';            Filename= "); Sb.            Append (Savename); Sb.            Append ("'"); Sb.            Append ("\ r \ n"); Sb.            Append ("Content-type:"); Sb.            Append ("Application/octet-stream"); Sb.            Append ("\ r \ n"); Sb.            Append ("\ r \ n"); String strpostheader = sb.            ToString ();            byte[] postheaderbytes = Encoding.UTF8.GetBytes (Strpostheader);            Creates a HttpWebRequest object based on a URI HttpWebRequest httpreq = (HttpWebRequest) webrequest.create (address);            Httpreq.method = "POST";            Do not use cache Httpreq.allowwritestreambuffering = False for sent data;            Set time-out for response (300 seconds) httpreq.timeout = 300000; Httpreq.contenttype = "Multipart/form-data;            boundary= "+ strboundary; Long length = fs.            Length + postheaderbytes.length + boundarybytes.length; Long filelength = fs.            Length; Httpreq.contentlength = length;                try {//upload 4k int bufferlength = 4096 each time;                byte[] buffer = new Byte[bufferlength];                Number of bytes uploaded long offset = 0;                Start upload time DateTime startTime = DateTime.Now;                int size = r.read (buffer, 0, bufferlength);                Stream Poststream = Httpreq.getrequeststream ();                Send Request Header Message Poststream.write (postheaderbytes, 0, postheaderbytes.length);                    while (Size > 0) {poststream.write (buffer, 0, size);                    Offset + = size;                    Application.doevents ();                Size = r.read (buffer, 0, bufferlength);                }//Add the trailing timestamp poststream.write (boundarybytes, 0, boundarybytes.length);                Poststream.close (); Gets the server-side response WebResponse webrespon = HttpreQ.getresponse ();                Stream s = Webrespon.getresponsestream ();                StreamReader sr = new StreamReader (s); Read the server-side returned message String sreturnstring = Sr.                ReadLine ();                S.close (); Sr.                Close ();                if (sreturnstring = = "Success") {returnvalue = 1;                } else if (sreturnstring = = "Error") {returnvalue = 0;            }} catch {returnvalue = 0; } finally {fs.                Close ();            R.close ();        } return returnvalue; }

  

ASP. NET MVC receives the compressed package and extracts:

<summary>///        Receive file Compression Package///</summary>//        <returns></returns>        [HttpPost ] public        contentresult receiveprojectfile ()        {            var result = "Success";            Try            {                if (Request.Files.Count < 1)                {                    result = "Error";                    return Content (result);;                }                HttpPostedFileBase file = request.files[0];                String filePath = Server.MapPath ("~/server") + "/" + file. FileName;                File. SaveAs (FilePath);                Unzipfile (FilePath, Server.MapPath ("~/server") + "/" + file. Filename.substring (0,file. Filename.indexof (". zip")));            }            catch (Exception)            {                result = "Error";            }            return Content (result);        }

  

 <summary>/////</summary>/<param name= "TargetFile" > Files to be unzipped </param>  <param name= "Filedir" > Decompression path </param>//<returns></returns> public string            Unzipfile (String targetfile, String filedir) {string rootfile = ""; try {//Read compressed file (zip file), prepare to decompress zipinputstream s = new Zipinputstream (System.IO.File.                OpenRead (Targetfile.trim ()));                ZipEntry Theentry;                string path = Filedir;                Unzip the file to save the path of string rootdir = "";  The name of the first subfolder under the root directory while ((Theentry = S.getnextentry ()) = null) {RootDir                    = Path.getdirectoryname (Theentry.name); Get the name of the first-level subfolder under the root directory if (rootdir.indexof ("\ \") >= 0) {root Dir = rootdir.substring (0, rootdir.indexof ("\ \") + 1);                    } String dir = Path.getdirectoryname (theentry.name);                    The name of the folder under the first-level subfolder under the root directory, string fileName = Path.getfilename (theentry.name);                        The file name under the root directory if (dir! = "")//Create a subfolder under the root directory, without limiting the level { if (!                            Directory.Exists (Filedir + "\" + dir) {path = Filedir + "\ \" + dir;                        Creates a folder Directory.CreateDirectory (path) in the specified path;                    }} else if (dir = = "" && fileName! = "")//files under the root directory                        {path = Filedir;                    RootFile = FileName;                    } else if (dir! = "" && fileName! = "")//root directory under the first level subfolder of the file                     {   if (dir. IndexOf ("\ \") > 0)//Specify the path to save the file {path = Filedi                        R + "\" + dir;                        }} if (dir = = RootDir)//Determine if it is necessary to save the file in the root directory {                    Path = Filedir + "\ \" + RootDir;                    }//The following is the basic procedure for extracting a ZIP file//The basic idea is to traverse all the files in the compressed file and create an identical file. if (fileName! = String.Empty) {FileStream streamWriter = System.IO.File.Create (                        Path + "\ \" + 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 ();                System.IO.File.Delete (targetfile);            return rootfile; } catch (Exception ex) {return "1;" + ex.            Message;    }        }

  

 

WinForm Program compressed file upload, server-side ASP-NET MVC to receive decompression

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.