private ResultUpload GetResultUploadBy(string xml) { if (string.IsNullOrEmpty(xml)) { throw new Exception("Informações de upload não informada"); } var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ResultUpload)); var fileName = Path.GetTempFileName(); File.WriteAllText(fileName, xml, Encoding.UTF8); var xmlDoc = new XmlTextReader(fileName); var resultUpload = new ResultUpload(); while (xmlDoc.Read()) { switch (xmlDoc.NodeType) { case XmlNodeType.Element: // The node is an element. if (xmlDoc.Name.Equals("upload")) { if (xmlDoc.HasAttributes) { resultUpload.url = xmlDoc.GetAttribute("url"); resultUpload.progress_url = xmlDoc.GetAttribute("progress_url"); resultUpload.max_file_size = xmlDoc.GetAttribute("max_file_size"); resultUpload.upload_identifier = xmlDoc.GetAttribute("upload_identifier"); resultUpload.extra_info = xmlDoc.GetAttribute("extra_info"); } return(resultUpload); } break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine(xmlDoc.Value); break; case XmlNodeType.EndElement: //Display the end of the element. Console.Write("</" + xmlDoc.Name); Console.WriteLine(">"); break; } } return(resultUpload); }
public ProgressUpload GetProgressUpload(ResultUpload resultUpload) { if (resultUpload == null) { throw new Exception("Dados upload não informado"); } var restClient = new RestClient(); var request = new RestRequest(resultUpload.progress_url, Method.GET); var progressUpload = restClient.Get <ProgressUpload>(request); return(progressUpload.Data); }
public async void UploadFileAsync(string fileName, ResultUpload resultUpload) { if (!File.Exists(fileName)) { throw new Exception("Arquivo não encontrado"); } RestRequest request = new RestRequest(resultUpload.url, Method.POST); var file = request.AddFile("userfile", File.ReadAllBytes(fileName), Path.GetFileName(fileName), "image/pjpeg"); request.AddParameter("MAX_FILE_SIZE", resultUpload.max_file_size); request.AddParameter("UPLOAD_IDENTIFIER", resultUpload.upload_identifier); request.AddParameter("extra_info", resultUpload.extra_info); //calling server with restClient RestClient restClient = new RestClient(); restClient.ExecuteAsync(request, (response) => { if (response.StatusCode == HttpStatusCode.OK) { //upload successfull SetProgressEventArgs(GetProgressUpload(resultUpload), true); } else { //error ocured during upload } }); var _statusProgress = GetProgressUpload(resultUpload).Status; while (_statusProgress.ToLower().Equals("ok")) { var progressInternal = GetProgressUpload(resultUpload); SetProgressEventArgs(progressInternal, false); _statusProgress = progressInternal.Status; } }
public ActionResult UploadHB() { List <ResultUpload> result = new List <ResultUpload>(); try { HttpPostedFileBase postedFileBase = Request.Files[0]; //2.png string fileName = postedFileBase.FileName; // 获取指定目录绝对路径,如果不存在,则创建 if (!Directory.Exists(TepmoraryPath)) { Directory.CreateDirectory(TepmoraryPath); } //string pathFile = TepmoraryPath + Guid.NewGuid().ToString() + Path.GetExtension(fileName); string pathFile = TepmoraryPath + fileName; var searchpattern = fileName.Split('.')[0] + "*." + fileName.Split('.')[1]; var count = Directory.GetFiles(TepmoraryPath, searchpattern); if (count.Length > 0) { pathFile = pathFile.Split('.')[0] + count.Length + '.' + pathFile.Split('.')[1]; } postedFileBase.SaveAs(pathFile); string guid = Guid.NewGuid().ToString(); //获取文件大小 var file = new FileInfo(pathFile); if (IsOpenHbUpload == "1") { string responseContent = UploadFile(pathFile, fileName); if (!string.IsNullOrEmpty(responseContent)) { ResultUpload upload = JsonConvert.DeserializeObject <ResultUpload>(responseContent);//将文件信息json字符 upload.GuidId = guid; upload.errorCode = "0"; upload.errorString = ""; upload.Name = fileName; upload.Size = GetLength(file.Length); upload.UploadName = UCode; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = upload.ResponseObject.responseObject[0]; obj.FDFS_NAME = upload.ResponseObject.responseObject[1]; upload.ResponseObject = obj; result.Add(upload); } } else { ResultUpload upload = new ResultUpload(); upload.GuidId = guid; upload.errorCode = "0"; upload.errorString = ""; upload.Name = fileName; upload.Size = GetLength(file.Length); upload.UploadName = UCode; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = string.Empty; obj.FDFS_NAME = pathFile; upload.ResponseObject = obj; result.Add(upload); } #region 生成缩略图 if (MakeThumbnail == "1" && ImageHelper.IsImage(Path.GetExtension(fileName))) { string thumbnailPath = ConfigurationManager.AppSettings["ThumbnailPath"]; if (!string.IsNullOrWhiteSpace(thumbnailPath)) { if (!thumbnailPath.EndsWith("\\")) { thumbnailPath += "\\"; } //拼接相对路径 string RelativePath = thumbnailPath.Substring(0, thumbnailPath.Length - 1); RelativePath = string.Format("{0}\\{1}\\{2}\\", RelativePath.Substring(RelativePath.LastIndexOf("\\") + 1), DateTime.Today.Year, DateTime.Today.Month); // 缩略图存储文件夹按年月格式生成 thumbnailPath = string.Format("{0}{1}\\{2}\\", thumbnailPath, DateTime.Today.Year, DateTime.Today.Month); if (!Directory.Exists(thumbnailPath)) { Directory.CreateDirectory(thumbnailPath); } string smallReName = string.Format("{0}{1}", Small, Guid.NewGuid() + fileName); if (file.Length < 1024 * 200) { System.IO.File.Copy(pathFile, thumbnailPath + smallReName); } else { //ImageHelper.MakeThumbnailImage(pathFile, thumbnailPath + smallReName, 300, 300, ImageHelper.ImageCutMode.Cut); ImageHelper.CompressImage(pathFile, thumbnailPath + smallReName); } ResultUpload upload = new ResultUpload(); upload.errorCode = "0"; upload.errorString = ""; upload.GuidId = guid; upload.Name = smallReName; upload.Size = GetLength(file.Length); upload.UploadName = UCode; upload.UploadDate = DateTime.Now; upload.ImageType = Small; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = ""; obj.FDFS_NAME = RelativePath.Replace("\\", "/") + smallReName; upload.ResponseObject = obj; result.Add(upload); #region 内网上传图片,缩略图发送给DMZ区服务器 if (IsOpenHbUpload == "1" && !IsNetwork) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UploadUrlThumbnail + "?fileName=" + string.Format("{0}\\{1}\\{2}", DateTime.Today.Year, DateTime.Today.Month, smallReName)); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = 600000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // Header const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, "filepath", thumbnailPath + smallReName); var headerbytes = Encoding.UTF8.GetBytes(header); // 写入文件 var fileStream = new FileStream(thumbnailPath + smallReName, FileMode.Open, FileAccess.Read); var memStream = new MemoryStream(); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); var buffer = new byte[fileStream.Length]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } // 写入字符串的Key Dictionary <string, string> dicr = new Dictionary <string, string>(); dicr.Add("status", "1"); var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string key in dicr.Keys select string.Format(stringKeyHeader, key, dicr[key]) into formitem select Encoding.UTF8.GetBytes(formitem)) { memStream.Write(formitembytes, 0, formitembytes.Length); } // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); memStream.Write(endBoundary, 0, endBoundary.Length); memStream.Position = 0; webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); fileStream.Close(); webRequest.Abort(); } #endregion } } #endregion if (IsOpenHbUpload == "1") { // 上传成功后, 删除临时文件 System.IO.File.Delete(pathFile); } } catch (Exception ex) { throw ex; } return(Json(result)); }
public ActionResult UploadHB() { List <ResultUpload> result = new List <ResultUpload>(); try { HttpPostedFileBase postedFileBase = Request.Files[0]; //2.png string fileName = postedFileBase.FileName; //.png string extension = Path.GetExtension(fileName); string fullPath = ConfigurationManager.AppSettings["TepmoraryPath"]; // 获取指定目录绝对路径,如果不存在,则创建 if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } string pathFile = fullPath + Guid.NewGuid().ToString() + extension; postedFileBase.SaveAs(pathFile); //用户编码 string ucode = CurrentUser.UserCode; //Guid string GuidId = Guid.NewGuid().ToString(); #region 务器 if (IsOpenHbUpload == "1") { #region 附件上传到本省资源服务器 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UploadUrl + "?RequestParam={%22Param%22:{%22envRoot%22:{%22UserName%22:%22" + ucode + "%22,%22Product%22:%22BIM%22},%22paramRoot%22:{%22FILE_NAME%22:%22" + fileName + "%22}}}"); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = 600000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // Header const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, "filepath", pathFile); var headerbytes = Encoding.UTF8.GetBytes(header); // 写入文件 var fileStream = new FileStream(pathFile, FileMode.Open, FileAccess.Read); var memStream = new MemoryStream(); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); var buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } // 写入字符串的Key Dictionary <string, string> dicr = new Dictionary <string, string>(); dicr.Add("status", "1"); var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string key in dicr.Keys select string.Format(stringKeyHeader, key, dicr[key]) into formitem select Encoding.UTF8.GetBytes(formitem)) { memStream.Write(formitembytes, 0, formitembytes.Length); } // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); memStream.Write(endBoundary, 0, endBoundary.Length); memStream.Position = 0; webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); string responseContent; var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } fileStream.Close(); httpWebResponse.Close(); webRequest.Abort(); //responseStr = "{\"addinObject\":null,\"errorCode\":0,\"errorString\":\"上传成功!\",\"exceptoin\":null,\"responseMap\":{\"osplicense\":\"TRUE\"},\"responseObject\":{\"addinObject\":null,\"errorCode\":0,\"errorString\":\"上传成功!\",\"exceptoin\":null,\"responseMap\":{\"osplicense\":\"TRUE\"},\"responseObject\":[\"group1\",\"M00/00/6E/Cs6Bz1ufFDeAc58CAAAIXkl8ijg320.jpg\"]}}"; //responseStr = "{\"addinObject\":null,\"errorCode\":0,\"errorString\":\"上传成功!\",\"exceptoin\":null,\"responseMap\":{\"osplicense\":\"TRUE\"},\"responseObject\":{\"addinObject\":null,\"errorCode\":0,\"errorString\":\"上传成功!\",\"exceptoin\":null,\"responseMap\":{\"osplicense\":\"TRUE\"},\"responseObject\":[\"group1\",\"M00/00/6E/Cs6Bz1ufE3mAbEoHAAAHDJ7WfBM330.txt\"]}}"; if (!string.IsNullOrEmpty(responseContent)) { ResultUpload upload = JsonConvert.DeserializeObject <ResultUpload>(responseContent);//将文件信息json字符 //获取文件大小 var file = new FileInfo(pathFile); var size = GetLength(file.Length); upload.GuidId = Guid.NewGuid().ToString(); upload.errorCode = "0"; upload.errorString = ""; upload.Name = fileName; upload.Size = size; upload.UploadName = CurrentUser.UserName; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = upload.ResponseObject.responseObject[0]; obj.FDFS_NAME = upload.ResponseObject.responseObject[1]; upload.ResponseObject = obj; result.Add(upload); } #endregion } else { //获取文件大小 var file = new FileInfo(pathFile); var size = GetLength(file.Length); ResultUpload upload = new ResultUpload(); upload.errorCode = "0"; upload.errorString = ""; upload.GuidId = GuidId; upload.Name = fileName; upload.Size = size; upload.UploadName = CurrentUser.UserName; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = "epm"; obj.FDFS_NAME = pathFile; upload.ResponseObject = obj; result.Add(upload); } #endregion #region 生成缩略图 if (MakeThumbnail == "1" && ImageHelper.IsImage(extension)) { string thumbnailPath = ConfigurationManager.AppSettings["ThumbnailPath"]; if (!string.IsNullOrWhiteSpace(thumbnailPath)) { if (!thumbnailPath.EndsWith("\\")) { thumbnailPath += "\\"; } //拼接相对路径 string RelativePath = thumbnailPath.Substring(0, thumbnailPath.Length - 1); RelativePath = string.Format("{0}\\{1}\\{2}\\", RelativePath.Substring(RelativePath.LastIndexOf("\\") + 1), DateTime.Today.Year, DateTime.Today.Month); // 缩略图存储文件夹按年月格式生成 thumbnailPath = string.Format("{0}{1}\\{2}\\", thumbnailPath, DateTime.Today.Year, DateTime.Today.Month); if (!Directory.Exists(thumbnailPath)) { Directory.CreateDirectory(thumbnailPath); } string smallReName = string.Format("{0}{1}", Small, Guid.NewGuid() + fileName); //ImageHelper.MakeThumbnailImage(pathFile, thumbnailPath + smallReName, 300, 300, ImageHelper.ImageCutMode.Cut); ImageHelper.CompressImage(pathFile, thumbnailPath + smallReName); //获取文件大小 var file = new FileInfo(thumbnailPath.Replace("\\", "/") + smallReName); var size = GetLength(file.Length); ResultUpload upload = new ResultUpload(); upload.errorCode = "0"; upload.errorString = ""; upload.GuidId = GuidId; upload.Name = smallReName; upload.Size = size; upload.UploadName = CurrentUser.UserName; upload.UploadDate = DateTime.Now; upload.ImageType = Small; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = ""; obj.FDFS_NAME = RelativePath.Replace("\\", "/") + smallReName; upload.ResponseObject = obj; result.Add(upload); } } #endregion if (IsOpenHbUpload == "1") { // 上传成功后, 删除临时文件 System.IO.File.Delete(pathFile); } } catch (Exception ex) { throw ex; } return(Json(result)); }
public ActionResult UploadHB() { List <ResultUpload> result = new List <ResultUpload>(); try { HttpPostedFileBase postedFileBase = Request.Files[0]; //2.png string fileName = postedFileBase.FileName; if (IsNetwork) { string TepmoraryPath = ConfigurationManager.AppSettings["TepmoraryPath"]; if (string.IsNullOrWhiteSpace(TepmoraryPath)) { throw new Exception("未配置资源存放路径!"); } // 获取指定目录绝对路径,如果不存在,则创建 if (!Directory.Exists(TepmoraryPath)) { Directory.CreateDirectory(TepmoraryPath); } string pathFile = TepmoraryPath + Guid.NewGuid().ToString() + Path.GetExtension(fileName); postedFileBase.SaveAs(pathFile); string responseContent = UploadFile(pathFile, fileName); if (!string.IsNullOrEmpty(responseContent)) { ResultUpload upload = new ResultUpload(); //获取文件大小 var file = new FileInfo(pathFile); var size = GetLength(file.Length); upload.GuidId = Guid.NewGuid().ToString(); upload.errorCode = "0"; upload.errorString = ""; upload.Name = fileName; upload.Size = size; upload.UploadName = UCode; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = ""; obj.FDFS_NAME = responseContent; upload.ResponseObject = obj; result.Add(upload); } // 上传成功后, 删除临时文件 System.IO.File.Delete(pathFile); } else { string TepmoraryPath = ConfigurationManager.AppSettings["BIMPath"]; if (string.IsNullOrWhiteSpace(TepmoraryPath)) { throw new Exception("未配置资源存放路径!"); } if (!Directory.Exists(TepmoraryPath)) { Directory.CreateDirectory(TepmoraryPath); } string pathFile = TepmoraryPath + fileName; postedFileBase.SaveAs(pathFile); //获取文件大小 var file = new FileInfo(pathFile); var size = GetLength(file.Length); ResultUpload upload = new ResultUpload(); upload.GuidId = Guid.NewGuid().ToString(); upload.errorCode = "0"; upload.errorString = ""; upload.Name = fileName; upload.Size = size; upload.UploadName = UCode; upload.UploadDate = DateTime.Now; ResponseObject obj = new ResponseObject(); obj.FDFS_GROUP = ""; obj.FDFS_NAME = pathFile; upload.ResponseObject = obj; result.Add(upload); } } catch (Exception ex) { throw ex; } return(Json(result)); }
/// <summary> /// 附件上传 /// <para>1. 如果启用图片压缩,在上传图片的时候会同步生成缩略图图片并保存</para> /// <para>2. 目前缩略图存储路径默认为站点根目录下,且发布时无需单独发布,可以直接访问</para> /// </summary> /// <param name="context">HttpContext 上下文</param> /// <param name="user">当前用户</param> /// <param name="columnName">附件功能区分</param> /// <returns></returns> public static List <Base_Files> UploadFile(HttpContext context, UserView user, string columnName = "") { List <Base_Files> fileList = new List <Base_Files>(); HttpFileCollection filesCollection = context.Request.Files; if (filesCollection.Count > 0) { try { int j = 0; Dictionary <string, List <HttpPostedFile> > dictionary = new Dictionary <string, List <HttpPostedFile> >(); foreach (string fileKey in filesCollection) { HttpPostedFile httpPostedFile = filesCollection[j]; var key = fileKey; if (!dictionary.ContainsKey(key)) { dictionary.Add(key, new List <HttpPostedFile>() { httpPostedFile }); } else { var files = dictionary[key]; files.Add(httpPostedFile); dictionary[key] = files; } j++; } foreach (var item in dictionary) { List <HttpPostedFile> httpPostedFileList = item.Value; for (int m = 0; m < httpPostedFileList.Count; m++) { HttpPostedFile httpPostedFile = httpPostedFileList[m]; string fileName = httpPostedFile.FileName; string extension = Path.GetExtension(fileName); string key = item.Key; string fullPath = ConfigurationManager.AppSettings["TepmoraryPath"]; if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } string pathFile = fullPath + Guid.NewGuid() + extension; httpPostedFile.SaveAs(pathFile); string guid = Guid.NewGuid().ToString(); //获取文件大小 var file = new FileInfo(pathFile); #region 务器 // 判断是否启用本省资源服务器 string hbResourceUrl = ConfigurationManager.AppSettings["useHbResourceUrl"]; if ("false".Equals(hbResourceUrl)) { Base_Files newFile = new Base_Files(); newFile.TableName = ""; newFile.TableId = 0; newFile.TableColumn = (key == "stop" ? "Stop" : (key == "meeting" ? "Meeting" : key)); newFile.Name = fileName; newFile.Size = GetLength(file.Length); newFile.UploadUserId = user.UserId; newFile.OperateUserId = user.UserId; newFile.OperateTime = DateTime.Now; newFile.IsDelete = false; newFile.CreateUserId = user.UserId; newFile.CreateTime = DateTime.Now; newFile.CreateUserName = user.RealName; newFile.OperateUserName = user.RealName; newFile.Url = pathFile; newFile.GuidId = guid; fileList.Add(newFile); } else { #region 本省服务器 string ucode = user.UserCode; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UploadUrlBase + "?fileName=" + fileName + "&RequestParam={%22Param%22:{%22envRoot%22:{%22UserName%22:%22" + ucode + "%22,%22Product%22:%22BIM%22},%22paramRoot%22:{%22FILE_NAME%22:%22" + fileName + "%22}}}"); // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // 设置属性 webRequest.Method = "POST"; webRequest.Timeout = 600000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // Header const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; var header = string.Format(filePartHeader, "filepath", pathFile); var headerbytes = Encoding.UTF8.GetBytes(header); // 写入文件 var fileStream = new FileStream(pathFile, FileMode.Open, FileAccess.Read); var memStream = new MemoryStream(); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); var buffer = new byte[fileStream.Length]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } // 写入字符串的Key Dictionary <string, string> dicr = new Dictionary <string, string>(); dicr.Add("status", "1"); var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string k in dicr.Keys select string.Format(stringKeyHeader, k, dicr[k]) into formitem select Encoding.UTF8.GetBytes(formitem)) { memStream.Write(formitembytes, 0, formitembytes.Length); } // 最后的结束符 var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); memStream.Write(endBoundary, 0, endBoundary.Length); memStream.Position = 0; webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); string responseContent; var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } fileStream.Close(); httpWebResponse.Close(); webRequest.Abort(); if (!string.IsNullOrEmpty(responseContent)) { ResultUpload result = JsonConvert.DeserializeObject <ResultUpload>(responseContent);//将文件信息json字符 Base_Files newFile = new Base_Files(); newFile.TableName = ""; newFile.TableId = 0; newFile.TableColumn = (key == "stop" ? "Stop" : (key == "meeting" ? "Meeting" : key)); newFile.Name = fileName; newFile.Size = GetLength(file.Length); newFile.UploadUserId = user.UserId; newFile.OperateUserId = user.UserId; newFile.OperateTime = DateTime.Now; newFile.IsDelete = false; newFile.CreateUserId = user.UserId; newFile.CreateTime = DateTime.Now; newFile.CreateUserName = user.RealName; newFile.OperateUserName = user.RealName; newFile.Url = result.ResponseObject.responseObject[1]; newFile.Group = result.ResponseObject.responseObject[0]; newFile.GuidId = guid; fileList.Add(newFile); } #endregion } #endregion #region 生成缩略图 // 生成缩略图 if (ImageHelper.IsImage(extension)) { string makeThumbnail = ConfigurationManager.AppSettings["MakeThumbnail"]; bool isMakeThumbnail = Boolean.TryParse(makeThumbnail, out isMakeThumbnail) ? isMakeThumbnail : false; /* * 缩略图存储路径处理和上传图片临时存储路径处理方式不同; * 缩略图存储路径在站点部署根目录下 */ if (isMakeThumbnail) { string thumbnailPath = ConfigurationManager.AppSettings["ThumbnailPath"]; if (!string.IsNullOrWhiteSpace(thumbnailPath)) { if (!thumbnailPath.EndsWith("\\")) { thumbnailPath += "\\"; } //拼接相对路径 string RelativePath = thumbnailPath.Substring(0, thumbnailPath.Length - 1); RelativePath = string.Format("{0}\\{1}\\{2}\\", RelativePath.Substring(RelativePath.LastIndexOf("\\") + 1), DateTime.Today.Year, DateTime.Today.Month); // 缩略图存储文件夹按年月格式生成 thumbnailPath = string.Format("{0}{1}\\{2}\\", thumbnailPath, DateTime.Today.Year, DateTime.Today.Month); if (!Directory.Exists(thumbnailPath)) { Directory.CreateDirectory(thumbnailPath); } string smallReName = string.Format("{0}{1}", Small, Guid.NewGuid() + fileName); if (file.Length < 1024 * 200) { File.Copy(pathFile, thumbnailPath + smallReName); } else { //ImageHelper.MakeThumbnailImage(pathFile, thumbnailPath + smallReName, 300, 300, ImageHelper.ImageCutMode.Cut); ImageHelper.CompressImage(pathFile, thumbnailPath + smallReName); } Base_Files newFile = new Base_Files(); newFile.TableName = ""; newFile.TableId = 0; newFile.TableColumn = (key == "stop" ? "Stop" : (key == "meeting" ? "Meeting" : key)); newFile.Name = smallReName; newFile.Size = GetLength(file.Length); newFile.UploadUserId = user.UserId; newFile.OperateUserId = user.UserId; newFile.OperateTime = DateTime.Now; newFile.IsDelete = false; newFile.CreateUserId = user.UserId; newFile.CreateTime = DateTime.Now; newFile.CreateUserName = user.RealName; newFile.OperateUserName = user.RealName; newFile.Url = RelativePath.Replace("\\", "/") + smallReName; newFile.GuidId = guid; newFile.ImageType = Small; fileList.Add(newFile); } } } #endregion if (!"false".Equals(hbResourceUrl)) { // 上传成功后, 删除临时文件 File.Delete(pathFile); } } } } catch (Exception ex) { } } return(fileList); }