標籤:.net開源 web service winform 檔案上傳下載
本章節主要講解HYAppFrame伺服器端如何ASP.NET Web Service實現檔案(含大檔案)上傳,WinForm用戶端如何下載檔案。
1 伺服器端檔案上傳1.1 上傳檔案
函數FileUpload(stringfileFullPath, byte[] file)用於上傳檔案,組建檔案前檢查檔案路徑所在檔案夾是否存在,不存在則首先建立檔案夾。
[WebMethod(EnableSession = true,Description = "上傳檔案")]public int FileUpload(string fileFullPath,byte[] file){ try { // 取得檔案夾 string dir = fileFullPath.Substring(0,fileFullPath.LastIndexOf("\\")); //如果不存在檔案夾,就建立檔案夾 if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); // 寫入檔案 File.WriteAllBytes(fileFullPath, file); return 1; } catch (Exception ex) { MyFuncLib.Log(ex.Message + "\r\n" + ex.StackTrace); return -1; }}1.2 合并檔案
經過實驗通過Web Service上傳檔案,如果大小超過2M可能遇到上傳失敗的錯誤,所以用戶端處理上傳大檔案時,先分割成小檔案,逐一上傳,然後再到伺服器上合并成原始檔案。
[WebMethod(EnableSession = true,Description = "合并檔案")]public int FileMerge(string fileFullPath,int num){ try { int i = 0; FileStream fs = new FileStream(fileFullPath, FileMode.Create,FileAccess.Write); while (num >= 0) { FileStream fsSource = new FileStream(fileFullPath + i, FileMode.Open,FileAccess.Read); Byte[] buffer = new Byte[fsSource.Length]; fsSource.Read(buffer, 0, Convert.ToInt32(fsSource.Length)); fs.Write(buffer, 0, buffer.Length); fsSource.Close(); num--; i++; } fs.Close(); // 刪除臨時檔案 while (i >= 0) { File.Delete(fileFullPath + i); i--; } return 1; } catch (Exception ex) { MyFuncLib.Log(ex.Message + "\r\n" + ex.StackTrace); return -1; }}1.3 刪除檔案
函數FileDelete(stringfileName)用於刪除給定檔案,刪除前要檢查使用者是否通過身分識別驗證,檢查給定的檔案路徑是否包含特殊符號,例如,如果包含連續兩個英文句號,使用者試圖操作其他路徑的檔案。刪除前,也要判斷檔案是否存在,刪除後判斷檔案是否仍然存在,以此判斷檔案是否真正被刪除。刪除成功返回1,未刪除任何檔案返回0。
[WebMethod(EnableSession= true, Description = "刪除指定檔案")]publicint FileDelete(string fileName){ try { if (!IsLogin()) return -100; fileName = MyFuncLib.WebDir +DES.Decrypt(fileName,MyFuncLib.passwordKey); // 不允許路徑指向其他目錄 if (fileName.IndexOf("..")> -1) return 0; // 如果是檔案夾,就跳過,不允許刪除檔案夾 if (Directory.Exists(fileName)) return 0; // 如果檔案存在刪除指定檔案 if (File.Exists(fileName)) File.Delete(fileName); if (File.Exists(fileName)) return 0; else return 1; } catch (Exception ex) { MyFuncLib.Log(ex.Message +"\r\n" + ex.StackTrace); return -1; }}2 用戶端檔案上傳下載2.1 檔案上傳
上傳檔案,支援多選,依次處理每一個檔案。當待處理檔案大小超過1M時,對其進行分割,並依次上傳,當全部檔案分割完畢後在伺服器上合并。當檔案上傳後,需將檔案的名稱、儲存路徑、大小、類型、關聯記錄id等屬性存入資料庫。
privatevoid UploadFile(){ try { this.progressBarX1.Value = 0; this.progressBarX1.Minimum = 0; string dirName = SysParameters.WebDir +webDir; OpenFileDialog ofg = newOpenFileDialog(); ofg.Title = "選擇檔案"; ofg.Filter = "所有檔案|*.*"; ofg.FilterIndex = 1; ofg.RestoreDirectory = true; ofg.Multiselect = true; if (ofg.ShowDialog() ==DialogResult.OK) { this.warningBox1.Text =string.Empty; foreach (string fileName inofg.FileNames) { #region 逐一處理上傳檔案 string newName =Guid.NewGuid().ToString() + MyFuncLib.getFileNameExt(fileName); using (FileStream fsSource =new FileStream(fileName, FileMode.Open, FileAccess.Read)) { // Read the source file into a bytearray. long size =fsSource.Length; if (size < int.MaxValue) this.progressBarX1.Maximum = (int)size; else this.progressBarX1.Maximum = int.MaxValue - 1; int unit = 1024000; //如果檔案體積小於1M,就一次性上傳,如果檔案大於1M就分割上傳 if (size <= unit) { byte[] bytes = newbyte[size]; int numBytesToRead =(int)size; int numBytesRead = 0; while (numBytesToRead> 0) { // Read may returnanything from 0 to numBytesToRead. int n =fsSource.Read(bytes, numBytesRead, numBytesToRead); // Break when theend of the file is reached. if (n == 0) break; numBytesRead += n; numBytesToRead -=n; } numBytesToRead =bytes.Length; MyFuncLib.WS.FileUpload(dirName + newName, bytes); this.progressBarX1.Value =(int)size; } else { //倍數 int multiple =(int)(size / unit); //餘數 int residue = (int)(size - multiple* unit); int i = 0; while (multiple > 0) { byte[] bytes = newbyte[unit]; int numBytesToRead= (int)unit; int numBytesRead =0; while(numBytesToRead > 0) { // Read mayreturn anything from 0 to numBytesToRead. int n =fsSource.Read(bytes, numBytesRead, numBytesToRead); // Break whenthe end of the file is reached. if (n == 0) break; numBytesRead +=n; numBytesToRead-= n; } numBytesToRead =bytes.Length; MyFuncLib.WS.FileUpload(dirName + newName + i, bytes); multiple--; i++; this.progressBarX1.Value = i * unit; } if (residue > 0) { byte[] bytes = newbyte[residue]; int numBytesToRead= (int)residue; int numBytesRead =0; while(numBytesToRead > 0) { // Read mayreturn anything from 0 to numBytesToRead. int n =fsSource.Read(bytes, numBytesRead, numBytesToRead); // Break whenthe end of the file is reached. if (n == 0) break; numBytesRead +=n; numBytesToRead-= n; } numBytesToRead =bytes.Length; MyFuncLib.WS.FileUpload(dirName + newName + i, bytes); } //在伺服器上合并檔案 MyFuncLib.WS.FileMerge(dirName + newName, i); } this.progressBarX1.Value =0; //將成功上傳的檔案寫入資料庫 if (this.cateName == null) this.cateName =string.Empty; string sql = "insertinto core_attachment() values()"; ArrayList sqlParams = newArrayList(); …… MyFuncLib.DBCommandExecNoneQueryBySql(sql, sqlParams); this.warningBox1.Text ="“" + fileName + "”檔案已上傳"; } #endregion } } } catch (Exception ex) { MyFuncLib.logToDB("error","系統錯誤", ex.Message, ex.StackTrace); MyFuncLib.msg("選擇檔案遇到錯誤,"+ ex.Message,"e"); }}2.2 檔案下載
函數Download(string url, string path)用於下載檔案。給定一個檔案網址,下載檔案並提供進度條支援。由於伺服器端使用IIS架設,ASP.NET Web Service提供服務的同時,本身也是一個Web網站,所以可通過一個網址下載伺服器上指定檔案。為了保證伺服器檔案安全,有兩個策略。首先設定IIS禁止列出檔案目錄,然後將上傳到伺服器的檔案使用GUID重新命名,由於GUID唯一性、無規律性,且比較複雜,所以伺服器上的檔案路徑不容易被猜測,從而保證檔案相對安全。
privateWebClient wc;privatevoid Download(string url, string path){ try { Uri uri = new Uri(url); wc = new WebClient(); wc.Proxy = null;//設定上網代理為空白 wc.DownloadFileCompleted += newAsyncCompletedEventHandler(webClient_DownloadFileCompleted); wc.DownloadProgressChanged += newDownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); wc.DownloadFileAsync(uri, path); this.label1.Text = "正在下載檔案“"+ oldName + "”"; } catch (Exception ex) { MyFuncLib.msg("錯誤:串連伺服器失敗,"+ ex.Message, "e"); }}privatevoid webClient_DownloadProgressChanged(object sender,DownloadProgressChangedEventArgs e){ this.progressBarX1.Value =e.ProgressPercentage;}privatevoid webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e){ try { // 下載完成後開啟指定檔案 System.Diagnostics.Process.Start(appPath + oldName); this.Close(); } catch (Exception ex) { MyFuncLib.msg("錯誤:開啟檔案失敗,"+ ex.Message, "e"); }}
Win Form + ASP.NET Web Service 檔案上傳下載--HYAppFrame