winform程式壓縮檔上傳,伺服器端asp.net mvc進行接收解壓

來源:互聯網
上載者:User

標籤:ror   rman   tor   output   tip   ctf   open   access   添加   

期間編程沒什麼難度,唯一可能忽略導致結果失敗是asp.net  mvc配置

對於壓縮檔大的話,需要配置mvc的最大接收量:

  <system.web>    <httpRuntime maxRequestLength="2147483647" executionTimeout="3600" />    <!--允許上傳資料大小->  </system.web> <system.webServer>    <!--允許上傳檔案長度,單位位元組-->    <security>       <requestFiltering>        <requestLimits maxAllowedContentLength="2147483647"/>      </requestFiltering>    </security> </system.webServer>

  

 

winform中壓縮和上傳:

調用部分如下:

string proPath = Application.StartupPath + "\\temp\\product\\" + project.ProjectName;ZipFile(proPath,proPath + ".zip");//壓縮var uploadResult = Upload_Request(WebConfig.UploadUrl + "/Mobile/ReceiveProjectFile", proPath + ".zip",project.ProjectName + ".zip");//上傳if (uploadResult == 0){LoadingForm.CloseLoadingCircle();Notification t = new Notification("方案附件上傳失敗,請重試!", 3, FormAnimator.AnimationMethod.Slide, FormAnimator.AnimationDirection.Up, true, "error");t.Show();return;}File.Delete(proPath + ".zip");

 

/// <summary>        /// 壓縮檔        /// </summary>        /// <param name="strFile">待壓縮檔路徑</param>        /// <param name="strZip">壓縮檔路徑</param>        public void ZipFile(string strFile, string strZip)        {            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)                strFile += Path.DirectorySeparatorChar;            ZipOutputStream s = new ZipOutputStream(File.Create(strZip));            s.SetLevel(6); // 0 - store only to 9 - means best compression            zip(strFile, s, strFile);            s.Finish();            s.Close();        }        private void zip(string strFile, ZipOutputStream s, string staticFile)        {            if (strFile[strFile.Length - 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 // 否則直接壓縮檔                {                    //開啟壓縮檔                    FileStream fs = File.OpenRead(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>        /// 將本地檔案上傳到指定的伺服器(HttpWebRequest方法)        /// </summary>        /// <param name="address">檔案上傳到的伺服器</param>        /// <param name="fileNamePath">要上傳的本地檔案(全路徑)</param>        /// <param name="saveName">檔案上傳後的名稱</param>        /// <returns>成功返回1,失敗返回0</returns>        private int Upload_Request(string address, string fileNamePath, string saveName)        {            int returnValue = 0;            // 要上傳的檔案            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);            BinaryReader r = new BinaryReader(fs);            //時間戳記            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");            //要求標頭部資訊            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);            // 根據uri建立HttpWebRequest對象            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);            httpReq.Method = "POST";            //對發送的資料不使用緩衝            httpReq.AllowWriteStreamBuffering = false;            //設定獲得響應的逾時時間(300秒)            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            {                //每次上傳4k                int bufferLength = 4096;                byte[] buffer = new byte[bufferLength];                //已上傳的位元組數                long offset = 0;                //開始上傳時間                DateTime startTime = DateTime.Now;                int size = r.Read(buffer, 0, bufferLength);                Stream postStream = httpReq.GetRequestStream();                //發送要求標頭部訊息                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);                while (size > 0)                {                    postStream.Write(buffer, 0, size);                    offset += size;                    Application.DoEvents();                    size = r.Read(buffer, 0, bufferLength);                }                //添加尾部的時間戳記                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);                postStream.Close();                //擷取伺服器端的響應                WebResponse webRespon = httpReq.GetResponse();                Stream s = webRespon.GetResponseStream();                StreamReader sr = new StreamReader(s);                //讀取伺服器端返回的訊息                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接收壓縮包,並解壓:

/// <summary>        /// 接收檔案壓縮包        /// </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">待解壓檔案</param>        /// <param name="fileDir">解壓路徑</param>        /// <returns></returns>        public string unZipFile(string TargetFile, string fileDir)        {            string rootFile = " ";            try            {                //讀取壓縮檔(zip檔案),準備解壓縮                ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(TargetFile.Trim()));                ZipEntry theEntry;                string path = fileDir;                //解壓出來的檔案儲存的路徑                string rootDir = " ";                //根目錄下的第一個子檔案夾的名稱                while ((theEntry = s.GetNextEntry()) != null)                {                    rootDir = Path.GetDirectoryName(theEntry.Name);                    //得到根目錄下的第一級子檔案夾的名稱                    if (rootDir.IndexOf("\\") >= 0)                    {                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);                    }                    string dir = Path.GetDirectoryName(theEntry.Name);                    //根目錄下的第一級子檔案夾的下的檔案夾的名稱                    string fileName = Path.GetFileName(theEntry.Name);                    //根目錄下的檔案名稱                    if (dir != " ")                    //建立根目錄下的子檔案夾,不限制層級                    {                        if (!Directory.Exists(fileDir + "\\" + dir))                        {                            path = fileDir + "\\" + dir;                            //在指定的路徑建立檔案夾                            Directory.CreateDirectory(path);                        }                    }                    else if (dir == " " && fileName != "")                    //根目錄下的檔案                    {                        path = fileDir;                        rootFile = fileName;                    }                    else if (dir != " " && fileName != "")                    //根目錄下的第一級子檔案夾下的檔案                    {                        if (dir.IndexOf("\\") > 0)                        //指定檔案儲存的路徑                        {                            path = fileDir + "\\" + dir;                        }                    }                    if (dir == rootDir)                    //判斷是不是需要儲存在根目錄下的檔案                    {                        path = fileDir + "\\" + rootDir;                    }                    //以下為解壓縮zip檔案的基本步驟                    //基本思路就是遍曆壓縮檔裡的所有檔案,建立一個相同的檔案。                    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程式壓縮檔上傳,伺服器端asp.net mvc進行接收解壓

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.