private UpLoadFileResult UpLoadPicture(System.IO.Stream file, string dirPath, string fileName = "") { UpLoadFileResult upLoadFileResult = new UpLoadFileResult(); string encodingName = "utf-8"; string imgType = string.Empty; List <string> typeList = new List <string>() { "JPG", "BMP", "PNG", "JPEG" }; using (MemoryStream ms = new MemoryStream()) { file.CopyTo(ms); ms.Position = 0; var encoding = Encoding.GetEncoding(encodingName); var reader = new StreamReader(ms, encoding); var headerLength = 0L; //读取第一行 var firstLine = reader.ReadLine(); //计算偏移(字符串长度+回车换行2个字符) headerLength += encoding.GetBytes(firstLine).LongLength + 2; //读取第二行 var secondLine = reader.ReadLine(); //计算偏移(字符串长度+回车换行2个字符) headerLength += encoding.GetBytes(secondLine).LongLength + 2; //解析文件名 string orgFileName = new System.Text.RegularExpressions.Regex("filename=\"(?<fn>.*)\"").Match(secondLine).Groups["fn"].Value; if (string.IsNullOrEmpty(fileName)) { fileName = orgFileName; } else { fileName = orgFileName.Replace(orgFileName.Substring(0, orgFileName.LastIndexOf('.')), fileName); } //判断图片格式 imgType = fileName.Substring(fileName.LastIndexOf('.') + 1).ToUpper(); if (!typeList.Contains(imgType)) { upLoadFileResult.FileName = "errorType"; upLoadFileResult.success = false; return(upLoadFileResult); } //一直读到空行为止 while (true) { //读取一行 var line = reader.ReadLine(); //若到头,则直接返回 if (line == null) { break; } //若未到头,则计算偏移(字符串长度+回车换行2个字符) headerLength += encoding.GetBytes(line).LongLength + 2; if (line == "") { break; } } //设置偏移,以开始读取文件内容 ms.Position = headerLength; ////减去末尾的字符串:“/r/n--/r/n” ms.SetLength(ms.Length - encoding.GetBytes(firstLine).LongLength - 3 * 2); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } string path = Path.Combine(dirPath, fileName); using (FileStream fileToupload = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read)) { ms.CopyTo(fileToupload); fileToupload.Flush(); } upLoadFileResult.FileName = fileName; upLoadFileResult.success = true; } return(upLoadFileResult); }