asp.net微信开发(高级群发图文)(2)

/// <summary> /// /// </summary>上传图片文件 /// <param></param> /// <param></param> protected void LinkBtnFileUploadImg_Click(object sender, EventArgs e) { if (this.FileUploadImg.HasFile) { string fileContentType = FileUploadImg.PostedFile.ContentType; if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg" || fileContentType == "image/pjpeg") { int fileSize = this.FileUploadImg.PostedFile.ContentLength; if (fileSize <=2097152) { string fileName = this.FileUploadImg.PostedFile.FileName; // 客户端文件路径 string filepath = FileUploadImg.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName; //得到上传的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg this.ImgTuWen.ImageUrl = "~/WeiXinImg/" + FileUploadImg.FileName; this.ImgTuWen2.Visible = true; this.ImgTuWen2.ImageUrl = "~/WeiXinImg/" + FileUploadImg.FileName; this.FileUploadImg.PostedFile.SaveAs(serverpath);//将上传的文件另存为 this.LinkBtnDeleteImg.Visible = true; Session["fileNameimg"] = this.FileUploadImg.PostedFile.FileName; //上传临时图片素材至微信服务器,3天后微信服务器会自动删除 WeiXinServer wxs = new WeiXinServer(); ///从缓存读取accesstoken string Access_token = Cache["Access_token"] as string; if (Access_token == null) { //如果为空,重新获取 Access_token = wxs.GetAccessToken(); //设置缓存的数据7000秒后过期 Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration); } string Access_tokento = Access_token.Substring(17, Access_token.Length - 37); //WebClient wx_upload = new WebClient(); //wx_upload.Credentials = CredentialCache.DefaultCredentials; string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", Access_tokento, "image"); string result = HttpUploadFile(url, serverpath); if (result.Contains("media_id")) { //使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(result); Session["imgmedia_id"] = jsonObj["media_id"].ToString(); } Response.Write("<script>alert('上传图片成功!')</script>"); } else { Response.Write("<script>alert('上传文件不能大于2M!')</script>"); } } else { Response.Write("<script>alert('只支持BMP,GIF,PNG,JPG格式的图片!')</script>"); } } else { Response.Write("<script>alert('请选择图片!')</script>"); } } /// <summary> /// Http上传文件 /// </summary> public static string HttpUploadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); //请求头部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.GetRequestStream(); postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close(); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } /// <summary> /// 删除图片 /// </summary> /// <param></param> /// <param></param> protected void LinkBtnDeleteImg_Click(object sender, EventArgs e) { string filename = Session["fileNameimg"].ToString(); if (!string.IsNullOrEmpty(filename))//确保picPath有值并且不为空。 { string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg if (File.Exists(serverpath)) { try { File.Delete(serverpath); this.ImgTuWen.ImageUrl = "weixinimg/fengmiandefault.jpg"; this.ImgTuWen2.Visible = false; this.ImgTuWen2.ImageUrl = ""; Session["fileNameimg"] = null; this.LinkBtnDeleteImg.Visible = false; } catch(Exception ex) { //错误处理: Response.Write(ex.Message.ToString()); } } } }

新建单图文预览代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwjxw.html