標籤:
接著上次寫.......................
這次利用wcf rest 上傳檔案.廢話不多說.接著寫代碼.
在上次的介面中添加上傳檔案方法UpLoad,代碼如下:
[WebInvoke(Method = "POST", UriTemplate = "UpLoad/{fileName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] [System.ComponentModel.Description("上傳檔案")] bool UpLoad(System.IO.Stream stream, string fileName);
然後編寫介面的方法實現:
public bool UpLoad(Stream stream, string fileName) { try { byte[] buffer = new byte[1024]; FileStream fs = new FileStream(@"d:\test\" + fileName, FileMode.Create, FileAccess.Write); int count = 0; while ((count = stream.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, count); } //清空緩衝區 fs.Flush(); //關閉流 fs.Close(); return true; } catch (Exception ex) { LogHelper.Error("儲存檔案失敗", ex); return false; } }
這裡儲存的路徑,我就固定到d:\test檔案夾下面.然後在瀏覽器裡面查看一下.
接下來就編寫用戶端代碼進行調用.接著上次的控制台應用程式寫.代碼如
public static void UploadFile() { Console.WriteLine("--------------上傳檔案----------------"); HttpClient httpClient = new HttpClient(); string uri = "http://localhost:31572/Service1.svc/UpLoad/"; try { string str; do { Stopwatch stopwatch = new Stopwatch(); Console.WriteLine("請輸入上傳檔案路徑:"); string filePath = Console.ReadLine(); if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { string fileName = filePath.Substring(filePath.LastIndexOf("\\", StringComparison.Ordinal)+1); Console.WriteLine("開始上傳檔案..."); Stream fs = new FileStream(filePath, FileMode.Open); HttpContent content = new StreamContent(fs); stopwatch.Start(); var response = httpClient.PostAsync(uri + fileName, content); response.Result.EnsureSuccessStatusCode(); Console.WriteLine("檔案:{0},上傳結果:{1}", fileName, response.Result.Content.ReadAsStringAsync().Result); Console.WriteLine("上傳檔案所需時間:{0}", stopwatch.ElapsedMilliseconds); } else { Console.WriteLine("請輸入正確的檔案路徑"); } Console.WriteLine("y/n是否繼續上傳?"); str = Console.ReadLine(); } while (str=="y"); } catch (Exception ex) { Console.WriteLine(ex); Console.Read(); } }
最後效果如:
下一篇就是soap和rest如何一起使用.
wcf rest 服務用於安卓和ISO調用2-------檔案上傳