很多時候,在上傳文件的時候會保存文件的信息以及一些其他的信息.現在我們就上傳一個用戶,並上傳文件.把需要上傳的數據寫到流裡面. 服務端解析流,取出我們需要的數據.流的的組成如下圖: 現在開始修改我們的upload方法.方法很簡單,就是依次從流裡面讀我們需要的數據來進行保存. public bool
很多時候,在上傳文件的時候會保存文件的信息以及一些其他的信息.現在我們就上傳一個用戶,並上傳文件.把需要上傳的數據寫到流裡面.
服務端解析流,取出我們需要的數據.流的的組成如下圖:
現在開始修改我們的upload方法.方法很簡單,就是依次從流裡面讀我們需要的數據來進行保存.
public bool UpLoad(Stream stream) { try { var modelStr = GetAnalysisResult(stream); //序列化json字元串為model var model = JsonConvert.DeserializeObject<Users>(modelStr); //保存文件 var fileList = WriteFile(stream); //保存model........ return true; } catch (Exception ex) { LogHelper.Error("保存文件失敗", ex); return false; } }
提供了大概的代碼.還有一些其他的方法.
private void WriteFile(Stream stream, string fileName, int fileCount) { if (!Directory.Exists(FileUrl)) Directory.CreateDirectory(FileUrl); //新建文件夾 using (var fs = new FileStream(FileUrl + fileName, FileMode.Create, FileAccess.Write)) //保存文件 { var buffer = getBytes(stream, fileCount); fs.Write(buffer, 0, buffer.Length); fs.Flush(); } } private byte[] getBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private string GetAnalysisResult(Stream stream) { var bytes = getBytes(stream, 4); var desLength = BitConverter.ToInt32(bytes, 0); //json字元串長度 var desModelStr = Encoding.UTF8.GetString(getBytes(stream, desLength)); //json字元串 return desModelStr; } private ICollection<MFileInfo> WriteFile(Stream stream) { ICollection<MFileInfo> fileCollection = new List<MFileInfo>(); //用於存放文件信息 while (true) { var fileDesLength = BitConverter.ToInt32(getBytes(stream, 4), 0); //獲取文件描述信息長度 if (fileDesLength == 0) { break; } var fileDesModelStr = Encoding.UTF8.GetString(getBytes(stream, fileDesLength)); //獲取文件描述信息 var fileInfo = fileDesModelStr.Split('|'); //拆分文件信息 var fileSuffix = fileInfo[0].Substring(fileInfo[0].LastIndexOf('.')); //文件尾碼名 var fileName = Guid.NewGuid().ToString().Replace("-", "") + fileSuffix; //重新生成文件名稱 var fileCount = Convert.ToInt32(fileInfo[1]); //文件大小 var fileType = Convert.ToInt32(fileInfo[2]); //文件類型(1:圖片2:視頻) WriteFile(stream, fileName, fileCount); //保存文件 fileCollection.Add(new MFileInfo { FileName = fileName, Length = fileCount, Type = fileType, FileSuffix = fileSuffix }); } return fileCollection; }
如果有多個文件就利用迴圈依次讀取.沒有的時候就退出迴圈.藉口的代碼就寫完了.接下來我們看看客戶端代碼.
public static async void UploadFile2() { Stopwatch stopwatch = new Stopwatch(); var jobj = new JObject(); jobj["Id"] = "4"; jobj["Name"] = "大師兄"; jobj["Gender"] = 1; string modelStr = jobj.ToString(); Console.WriteLine("請輸入上傳文件路徑:"); string filePath = Console.ReadLine(); stopwatch.Start(); if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { string fileName = filePath.Substring(filePath.LastIndexOf("\\", StringComparison.Ordinal) + 1); FileStream fs = new FileStream(filePath, FileMode.Open); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string fileDes = fileName + "|" + fs.Length + "|" + 1; var fileDesB = Encoding.UTF8.GetBytes(fileDes); byte[] fileDesBytes = BitConverter.GetBytes(fileDesB.Length); var desStr = Encoding.UTF8.GetBytes(modelStr); byte[] desBytes = BitConverter.GetBytes(desStr.Length); string url = "http://localhost:31572/Service1.svc/UpLoad"; WebRequest wRequest = WebRequest.Create(url); wRequest.Proxy = null; wRequest.Method = "POST"; wRequest.Timeout = 10000 * 100; wRequest.CachePolicy = null; var requestStream = wRequest.GetRequestStream(); await requestStream.WriteAsync(desBytes, 0, desBytes.Length); await requestStream.WriteAsync(desStr, 0, desStr.Length); await requestStream.WriteAsync(fileDesBytes, 0, fileDesBytes.Length); await requestStream.WriteAsync(fileDesB, 0, fileDesB.Length); await requestStream.WriteAsync(buffer, 0, buffer.Length); var response = await wRequest.GetResponseAsync(); Stream stream1 = response.GetResponseStream(); StreamReader reader = new StreamReader(stream1, Encoding.Default); string r = reader.ReadToEnd(); //url返回的值 stream1.Close(); response.Close(); stopwatch.Stop(); Console.WriteLine("文件上傳:{0}", r); Console.WriteLine("文件上傳時間:{0}", stopwatch.ElapsedMilliseconds); } }
文件上傳到這裡就結束了..........下一篇記錄一下簡單的身份驗證