winform程序壓縮文件上傳,服務器端asp.net mvc進行接收解壓
阿新 • • 發佈:2017-11-05
調用 第一個 iter return execution ucc inf each director
期間編程沒什麽難度,唯一可能忽略導致結果失敗是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進行接收解壓