做营销软件的时候,我们常会和织梦打交道,那么这里就给大家介绍个小方法,C#使用POST方法实现织梦(DedeCMS)图片上传。看程序运行截图
主程序代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; namespace POSTIMG { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void bt_liulan_Click(object sender, EventArgs e) { OpenFileDialog opf = new OpenFileDialog(); opf.Filter = "图片文件|*.jpg;*.gif;*.jpeg;*.png;*.bmp"; opf.Multiselect = false; if (opf.ShowDialog() == DialogResult.OK) tb_fpath.Text = opf.FileName; } private void bt_upload_Click(object sender, EventArgs e) { if (File.Exists(tb_fpath.Text.Trim())) { Thread t = new Thread(new ThreadStart(UpLoad)); t.IsBackground = true; t.Start(); } else MessageBox.Show("请重新选择图片"); } private void UpLoad() { CheckForIllegalCrossThreadCalls = false; XB xb = new XB("http://localhost/dedecms/dede/login.php","admin","admin"); string res = xb.login(); xb.login(); if (res.Contains("成功登录")) { res = xb.UpLoad(DateTime.Now.ToString("yyyyMMddHHmmss"),tb_fpath.Text.Trim(),tb_data.Text); tb_res.Text = res; //if (res.Contains("成功上传")) //{ // Invoke((EventHandler)delegate { MessageBox.Show("上传成功"); }); //}else // Invoke((EventHandler)delegate { MessageBox.Show("上传失败"); }); } else { Invoke((EventHandler)delegate { MessageBox.Show("登录失败,请重试"); }); } Thread.CurrentThread.Abort(); } private void button1_Click(object sender, EventArgs e) { //FileStream fs = new FileStream(tb_fpath.Text,FileMode.Open,FileAccess.Read); ////byte [] img= File.ReadAllBytes(tb_fpath.Text.Trim()); ////string s = Encoding.Default.GetString(img); //pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; //pictureBox1.Image = Image.FromStream(fs,false); byte[] i = File.ReadAllBytes(tb_fpath.Text); pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; pictureBox1.Image = convertImg(i); } private Image convertImg(byte[] datas) { MemoryStream ms = new MemoryStream(datas); Image img = Image.FromStream(ms, true);//在这里出错 ms.Close();//流用完要及时关闭 return img; } } }
然后看看类代码
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace POSTIMG { class XB { string username=""; string userpwd = ""; string hturl = ""; CookieContainer cookies = new CookieContainer(); public XB(string h,string u,string p) { username = u; userpwd = p; hturl = h; } /// <summary> /// POST提交 /// </summary> /// <param name="url">目标页面</param> /// <param name="fromstr">来路</param> /// <param name="data">要提交的数据</param> /// <returns></returns> public string Post(string url, string fromstr, string data) { Encoding enc = Encoding.GetEncoding("gb2312"); string RegStr = "系统错误,请重试";//返回的文字信息 try { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url); Request.Accept = "text/html, application/xhtml+xml, */*"; Request.Method = "post"; Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; Request.ContentType = "application/x-www-form-urlencoded"; Request.Referer = fromstr; Request.Headers["Accept-Language"] = "zh-cn"; string s = data; byte[] Shuju = enc.GetBytes(s); Request.ContentLength = Shuju.Length; //提交数据 Stream outstream = Request.GetRequestStream(); outstream.Write(Shuju, 0, Shuju.Length); outstream.Close(); //获取响应 HttpWebResponse res = (HttpWebResponse)Request.GetResponse(); if (res.StatusCode == HttpStatusCode.OK)//状态ok { //获取响应后的数据 StreamReader reader = new StreamReader(res.GetResponseStream(), enc); Char[] read = new Char[512]; int count = reader.Read(read, 0, 512); string str = null; while (count > 0) { str += new String(read, 0, count); count = reader.Read(read, 0, 512); } reader.Close(); outstream.Close(); res.Close(); RegStr = str; } } catch { RegStr = "系统错误,请重试"; } return RegStr; } public string login() { Encoding enc = Encoding.GetEncoding("gb2312"); string RegStr = "系统错误,请重试";//返回的文字信息 try { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(hturl); Request.Accept = "text/html, application/xhtml+xml, */*"; Request.Method = "post"; Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; Request.ContentType = "application/x-www-form-urlencoded"; Request.Referer = hturl; Request.Headers["Accept-Language"] = "zh-cn"; string s = "gotopage=%2Fdede%2Findex.php&dopost=login&adminstyle=newdedecms&userid=admin&pwd=admin"; byte[] Shuju = enc.GetBytes(s); Request.ContentLength = Shuju.Length; Request.CookieContainer = cookies; Stream outstream = Request.GetRequestStream(); outstream.Write(Shuju, 0, Shuju.Length); outstream.Close(); HttpWebResponse res = (HttpWebResponse)Request.GetResponse(); if (res.StatusCode == HttpStatusCode.OK)//状态ok { //获取响应后的数据 StreamReader reader = new StreamReader(res.GetResponseStream(), enc); Char[] read = new Char[512]; int count = reader.Read(read, 0, 512); string str = null; while (count > 0) { str += new String(read, 0, count); count = reader.Read(read, 0, 512); } foreach (Cookie ck in res.Cookies) cookies.Add(ck); reader.Close(); outstream.Close(); res.Close(); RegStr = str; } } catch { RegStr = "系统错误,请重试"; } return RegStr; } /// <summary> /// 图片上传 /// </summary> /// <param name="title">文件标题</param> /// <param name="filepath">本地路径</param> /// <returns></returns> public string UpLoad(string title,string filepath,string data) { Encoding enc = Encoding.GetEncoding("gb2312"); string RegStr = "系统错误,请重试";//返回的文字信息 try { HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("http://localhost/dedecms/dede/media_add.php"); Request.Accept = "text/html, application/xhtml+xml, */*"; Request.Method = "POST"; Request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; Request.ContentType = "multipart/form-data; boundary=---------------------------7dd173ed026c"; Request.Referer = "http://localhost/dedecms/dede/media_add.php"; Request.Headers["Accept-Language"] = "zh-cn"; Request.CookieContainer = cookies; string s = data.Remove(data.IndexOf("LYG"));//第一部分数据 s = s.Replace("[标题]", title); s = s.Replace("[文件名]",Path.GetFileName(filepath)); s = s.Replace("[地址]", "/uploads/allimg/130407/1_"+title+".jpg"); byte[] one = enc.GetBytes(s); string ss = data.Substring(data.IndexOf("LYG")+3); byte[] two = enc.GetBytes(ss); byte[] tupian = File.ReadAllBytes(filepath); byte[] ZH = new byte[one.Length+two.Length+tupian.Length]; one.CopyTo(ZH,0); tupian.CopyTo(ZH,one.Length); two.CopyTo(ZH,one.Length+tupian.Length); byte[] Shuju = ZH; Request.ContentLength = Shuju.Length; //提交数据 Stream outstream = Request.GetRequestStream(); outstream.Write(Shuju, 0, Shuju.Length); outstream.Close(); //获取响应 HttpWebResponse res = (HttpWebResponse)Request.GetResponse(); if (res.StatusCode == HttpStatusCode.OK)//状态ok { //获取响应后的数据 StreamReader reader = new StreamReader(res.GetResponseStream(), enc); Char[] read = new Char[512]; int count = reader.Read(read, 0, 512); string str = null; while (count > 0) { str += new String(read, 0, count); count = reader.Read(read, 0, 512); } reader.Close(); outstream.Close(); res.Close(); RegStr = str; } } catch { RegStr = "系统错误,请重试"; } return RegStr; } } }
============
首先是我们需要注意(织梦)程序的编码,还有关闭后台登录验证码。因为我们要实现上传的话必须要先登录我们的后台。其中重要的一点是图片上传时的POST数据格式
-----------------------------7dd173ed026c Content-Disposition: form-data; name="dopost" upload -----------------------------7dd173ed026c Content-Disposition: form-data; name="mediatype" 1 -----------------------------7dd173ed026c Content-Disposition: form-data; name="title" [标题] -----------------------------7dd173ed026c Content-Disposition: form-data; name="mediawidth" -----------------------------7dd173ed026c Content-Disposition: form-data; name="mediaheight" -----------------------------7dd173ed026c Content-Disposition: form-data; name="playtime" -----------------------------7dd173ed026c Content-Disposition: form-data; name="picnum" 5 -----------------------------7dd173ed026c Content-Disposition: form-data; name="upfile1"; filename="[文件名]" Content-Type: image/jpeg LYG -----------------------------7dd173ed026c Content-Disposition: form-data; name="upfile2"; filename="" Content-Type: application/octet-stream -----------------------------7dd173ed026c Content-Disposition: form-data; name="upfile3"; filename="" Content-Type: application/octet-stream -----------------------------7dd173ed026c Content-Disposition: form-data; name="upfile4"; filename="" Content-Type: application/octet-stream -----------------------------7dd173ed026c Content-Disposition: form-data; name="upfile5"; filename="" Content-Type: application/octet-stream -----------------------------7dd173ed026c Content-Disposition: form-data; name="imageField.x" 35 -----------------------------7dd173ed026c Content-Disposition: form-data; name="imageField.y" 19 -----------------------------7dd173ed026c--
其中中间的“LYG”表示图片数据的意思,用到了byte[]的拼接等。大家拿回去好好研究吧,经过测试是能成功上传的。源码放给大家