很多时候,在上传文件的时候会保存文件的信息以及一些其他的信息.现在我们就上传一个用户,并上传文件.把需要上传的数据写到流里面.
服务端解析流,取出我们需要的数据.流的的组成如下图:
现在开始修改我们的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); } }
文件上传到这里就结束了..........下一篇记录一下简单的身份验证