private async void btnUpload_Click(object sender, RibbonControlEventArgs e) { if (FormFactory.JWTToken == null) { MessageBox.Show("无服务器信息或身份验证未通过"); return; } if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtIntroduction.Text)) { MessageBox.Show("未填写模板名称或介绍"); return; } if (!Globals.ThisAddIn.Application.ActiveDocument.Saved) { var result = MessageBox.Show("保存当前文档?", "保存", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); if (!(result == DialogResult.OK)) { return; } Globals.ThisAddIn.Application.ActiveDocument.Save(); } string word = Globals.ThisAddIn.Application.ActiveDocument.FullName; string tempFile = new string(word.Take(word.LastIndexOf('\\')).ToArray()) + @"\temp.png"; await SaveImage(word, tempFile); TempletForJson templet = new TempletForJson() { TempletName = txtName.Text, TempletIntroduction = txtIntroduction.Text, TokenValue = FormFactory.JWTToken.TokenValue, StateCode = StateCode.request }; switch (cmbUploadType.Text) { case "公共模板": templet.Accessibility = Model.Accessibility.Public; break; case "私有模板": templet.Accessibility = Model.Accessibility.Private; break; case "组织模板": templet.Accessibility = Model.Accessibility.Protected; break; default: MessageBox.Show("模板类型信息不正确"); await FileHelper.DeleteAbsolute(tempFile); return; } StateMessage state = await WebHelper.UploadFile <StateMessage>(FormFactory.userMsg.IPAddress + "/JsonAPI/UploadWord", templet, new string[] { word, tempFile }); await FileHelper.DeleteAbsolute(tempFile); MessageBox.Show(state.StateDescription); }
/// <summary> /// 添加模板文件 /// </summary> /// <typeparam name="T">模板类型</typeparam> /// <param name="templet">模板实体</param> /// <param name="request">请求对象,用于获取上传的文件</param> /// <param name="service">数据服务对象</param> /// <param name="templetType">模板类型,首字母大写</param> /// <returns>插入结果</returns> public StateMessage SaveTemplet <T>(TempletForJson templet, HttpRequest request, IBaseService <T> service, string templetType) where T : BaseTemplet, new() { UserForTemplet user = new ValidateToken().CheckUser(templet.TokenValue.Trim());//token验证用户 if (user.StateCode != StateCode.normal) { return new StateMessage() { StateCode = user.StateCode, StateDescription = user.StateDescription } } ; UserInfo userInfo = ServiceSessionFactory.ServiceSession.UserInfoService.LoadEntity(u => u.ID == user.ID).FirstOrDefault();//查询用户以写数据库 if (userInfo == null) { return new StateMessage() { StateCode = StateCode.noUser, StateDescription = "token所指示的用户不存在" } } ; if ((userInfo.UserAuth != (UserAuth.Admin | UserAuth.Uploader)) && templet.Accessibility == Accessibility.Protected)//验证用户权限 { return new StateMessage() { StateCode = StateCode.permissionDenied, StateDescription = "权限不足" } } ; lock (ServiceSessionFactory.ServiceSession) //加锁防止请求并发时ID重复 { int tempID = service.LoadEntity(w => true).Max(w => w.ID) + 1; //取数据库中最大的ID+1作为新模板的ID, T word = new T() { ID = tempID, TempletName = templet.TempletName, TempletIntroduction = templet.TempletIntroduction, Accessibility = templet.Accessibility, ImagePath = "/Content/" + templetType + "/w" + tempID + ".png", FilePath = "/Content/" + templetType + "/w" + tempID + ".docx", ModTime = DateTime.Now, User = userInfo, Organization = userInfo.Organization ?? new OrganizationInfo() { ID = new Guid() } };//实例化插入对象 if (request.Files.Count != 2) { return new StateMessage() { StateCode = StateCode.noRequestError, StateDescription = "请求无附加文件或附加文件数量有误" } } ; request.Files[0].SaveAs(request.MapPath("/Content/" + templetType + "/w" + tempID + ".docx")); request.Files[1].SaveAs(request.MapPath("/Content/" + templetType + "/w" + tempID + ".png"));//存储文件 service.AddEntity(word); } return(new StateMessage() { StateCode = StateCode.normal, StateDescription = "上传成功" }); }
public ActionResult UploadVideo(TempletForJson templet) { return(Json(util.SaveTemplet(templet, System.Web.HttpContext.Current.Request, ServiceSessionFactory.ServiceSession.VideoService, "Video"))); }
/// <summary> /// 上传模板 /// </summary> /// <typeparam name="T">返回值的类型</typeparam> /// <param name="url">服务器地址</param> /// <param name="templet">上传的模板信息实体</param> /// <param name="filePath">文档路径和缩略图路径,顺序不能交换</param> /// <returns>服务端的返回信息</returns> public async static Task <T> UploadFile <T>(string url, TempletForJson templet, params string[] filePath) where T : StateMessage, new() { if (filePath.Length == 2) { return(await Task.Run(() => { #region 构建WebClient对象 using (WebClient client = new WebClient()) { if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3; } string responseContent; MemoryStream memStream = new MemoryStream(); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); #endregion #region 构建文件流对象 FileStream fileStream1 = new FileStream(filePath[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream fileStream2 = new FileStream(filePath[1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); #endregion #region 边界符 string boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); byte[] beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); #endregion #region 结束符 byte[] endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); #endregion #region 初始化Client属性,POST方式,超时时间和表单提交 webRequest.Method = "POST"; webRequest.Timeout = 2000; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; #endregion #region 写入文件1 const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; string header = string.Format(filePartHeader, "File1", filePath[0]);//构建参数头 byte[] headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(beginBoundary, 0, beginBoundary.Length); memStream.Write(headerbytes, 0, headerbytes.Length); //向流中写入参数头 var buffer = new byte[1024]; //创建缓冲区 int bytesRead; while ((bytesRead = fileStream1.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead);//读取文件内容 } #endregion #region 写入文件2 header = string.Format(filePartHeader, "File2", filePath[1]);//构建参数头 header = "\r\n--" + boundary + "\r\n" + header; headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length);//向流中写入参数头 while ((bytesRead = fileStream2.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } #endregion #region 写入所有其他字符参数 var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; Model.Accessibility Access = templet.Accessibility; Dictionary <string, string> stringDict = new Dictionary <string, string>(); stringDict.Add("TokenValue", templet.TokenValue); stringDict.Add("TempletName", templet.TempletName); stringDict.Add("TempletIntroduction", templet.TempletIntroduction); stringDict.Add("Accessibility", ((int)templet.Accessibility).ToString());//构建字典以遍历写入流信息 string str = ""; foreach (string formitem in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select formitem) { str += formitem; byte[] formitembytes = Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } #endregion #region 写入结束符 memStream.Write(endBoundary, 0, endBoundary.Length); #endregion #region 发送请求,获取结果并释放对象 webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { responseContent = httpStreamReader.ReadToEnd(); } fileStream1.Close(); fileStream2.Close(); httpWebResponse.Close(); webRequest.Abort(); #endregion return JsonConvert.DeserializeObject <T>(responseContent); } })); } else { return new T() { StateCode = StateCode.requestBodyError, StateDescription = "请求参数不正确" } }; }