微信活码初实现

此程序分客户端跟服务器端两个方面的代码

ASP.NET代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QRCode
{
    public partial class QRCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Files.Count > 0)
            {
                try
                {
                    HttpPostedFile file = Request.Files[0];
                    this.MapPath("UploadDocument");
                    string filePath = "D:\\QRCodes\\QRCodes\\QRCodes\\image\\" + file.FileName;
                    file.SaveAs(filePath);
                    Response.Write("Success");
                }
                catch
                {
                    Response.Write("Error");
                }
            }
            else
            {
                Response.Write("Error1");
            }  
        }

        public void FolderCreate(string Path)
        {
            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);
        }  
    }
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QRCode
{
    public partial class QRCodes : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["id"];
            if (id != null)
            {
                string sql = "Select top 1 * from weChatQRCodes where code=‘" + id + "‘ and num<100";
                DataTable dt = SqlHelper.ExecuteDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    Image1.ImageUrl = dt.Rows[0]["images"].ToString();
                    int i= Convert.ToInt32( dt.Rows[0]["num"])+1;
                    string sqlStr = "Update weChatQRCodes set num=" + i + " where id=‘" + dt.Rows[0]["id"] + "";
                    SqlHelper.ExecuteNonQuery(sqlStr);
                }
            }
        }
    }
}

客户端代码

微信活码初实现

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec;

namespace WeChatQRCode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string safeFilterName;
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            if (button1.Text == "打开图片")
            {
                open.InitialDirectory = "C\\";
                open.RestoreDirectory = true;
                open.FilterIndex = 1;
                open.Filter = "jpg文件(*.jpg)|*.jpg";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (open.Filter != null)
                        {
                            textBox1.Text = open.FileName;
                            safeFilterName = open.SafeFileName;
                            button1.Text = "上传图片";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("文件打开错误!" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            else
            {
                if (textBox3.Text == "")
                {
                    MessageBox.Show("请输入名称后再上传!");
                    textBox3.Focus();
                }
                else
                {
                    if (Upload_Request("http://chemishu.com.cn/QRCode.aspx", textBox1.Text, safeFilterName, progressBar1) == 1)
                    {
                        string sql = "insert into weChatQRCodes(code,images,num,picAdress,name) values(‘" + textBox2.Text + "‘,‘~\\image\\" + safeFilterName + "‘,1,‘http://chemishu.com.cn/image/" + safeFilterName + "‘,‘"+textBox3.Text+"‘)";
                        int i = SqlHelper.ExecuteNonQuery(sql);
                        if (i == 1)
                        {
                            MessageBox.Show("上传成功!");
                            lblSize.Visible = false;
                            lblSpeed.Visible = false;
                            lblState.Visible = false;
                            lblTime.Visible = false;
                            progressBar1.Visible = false;
                            button1.Text = "打开图片";
                            textBox1.Text = "";
                            textBox3.Text = "";
                        }
                        else
                        {
                            MessageBox.Show("上传成功,插入数据库失败!");
                            lblSize.Visible = false;
                            lblSpeed.Visible = false;
                            lblState.Visible = false;
                            lblTime.Visible = false;
                            progressBar1.Visible = false;
                            button1.Text = "打开图片";
                            textBox1.Text = "";
                            textBox3.Text = "";
                        }
                    }
                    else
                    {
                        MessageBox.Show("上传失败!");
                        lblSize.Visible = false;
                        lblSpeed.Visible = false;
                        lblState.Visible = false;
                        lblTime.Visible = false;
                        progressBar1.Visible = false;
                    }
                }
            }
        }

        /// <summary>   
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法)   
        /// </summary>   
        /// <param name="address">文件上传到的服务器</param>   
        /// <param name="fileNamePath">要上传的本地文件(全路径)</param>   
        /// <param name="saveName">文件上传后的名称</param>   
        /// <param name="progressBar">上传进度条</param>   
        /// <returns>成功返回1,失败返回0</returns>   
        private int Upload_Request(string address, string fileNamePath, string saveName, ProgressBar progressBar)
        {
            progressBar1.Visible = true;
            lblSize.Visible = true;
            lblSpeed.Visible = true;
            lblState.Visible = true;
            lblTime.Visible = true;
            int returnValue = 0;     // 要上传的文件   
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);     //时间戳   
            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");     //请求头部信息   
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(saveName);
            sb.Append("\";");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string strPostHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);     // 根据uri创建HttpWebRequest对象   
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
            httpReq.Method = "POST";     //对发送的数据不使用缓存   
            httpReq.AllowWriteStreamBuffering = false;     //设置获得响应的超时时间(300秒)   
            httpReq.Timeout = 300000;
            httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
            long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
            long fileLength = fs.Length;
            httpReq.ContentLength = length;
            try
            {
                progressBar.Maximum = int.MaxValue;
                progressBar.Minimum = 0;
                progressBar.Value = 0;
                //每次上传4k  
                int bufferLength = 4096;
                byte[] buffer = new byte[bufferLength]; //已上传的字节数   
                long offset = 0;         //开始上传时间   
                DateTime startTime = DateTime.Now;
                int size = r.Read(buffer, 0, bufferLength);
                Stream postStream = httpReq.GetRequestStream();         //发送请求头部消息   
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                while (size > 0)
                {
                    postStream.Write(buffer, 0, size);
                    offset += size;
                    progressBar.Value = (int)(offset * (int.MaxValue / length));
                    TimeSpan span = DateTime.Now - startTime;
                    double second = span.TotalSeconds;
                    lblTime.Text = "已用时:" + second.ToString("F2") + "";
                    if (second > 0.001)
                    {
                        lblSpeed.Text = "平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
                    }
                    else
                    {
                        lblSpeed.Text = " 正在连接…";
                    }
                    lblState.Text = "已上传:" + (offset * 100.0 / length).ToString("F2") + "%";
                    lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
                    Application.DoEvents();
                    size = r.Read(buffer, 0, bufferLength);
                }
                //添加尾部的时间戳   
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();         //获取服务器端的响应   
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                //读取服务器端返回的消息  
                StreamReader sr = new StreamReader(s);
                String sReturnString = sr.ReadLine();
                s.Close();
                sr.Close();
                if (sReturnString == "Success")
                {
                    returnValue = 1;
                }
                else if (sReturnString == "Error")
                {
                    returnValue = 0;
                }
            }
            catch
            {
                returnValue = 0;
            }
            finally
            {
                fs.Close();
                r.Close();
            } return returnValue;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            String data = "http://chemishu.com.cn/QRCodes.aspx?id=" + textBox2.Text;
            Image image = qrCodeEncoder.Encode(data, Encoding.UTF8);
            pictureBox1.Image = image;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|PnG Image|*.png|Wmf  Image|*.wmf";
            save.FilterIndex = 0;
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("没有预览图片");
            }
            else if (save.ShowDialog() == DialogResult.OK)
            {
                if (pictureBox1.Image != null)
                {
                    pictureBox1.Image.Save(save.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2();
            frm.code = textBox2.Text;
            frm.ShowDialog();
        }
    }
}

微信活码初实现

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace WeChatQRCode
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public string code;
        DataTable dt;
        int i;
        private void Form2_Load(object sender, EventArgs e)
        {
            string sql = "select * from weChatQRCodes where code=‘" + code + "";
            dt = SqlHelper.ExecuteDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                string url = dt.Rows[0]["picAdress"].ToString();
                pictureBox1.ImageLocation = dt.Rows[0]["picAdress"].ToString();
                lblnum.Text = dt.Rows[0]["num"].ToString();
                lblName.Text = dt.Rows[0]["name"].ToString();
                button1.Enabled = false;
                if (dt.Rows.Count == 1)
                {
                    button2.Enabled = false;
                }
                i = 0;
            }
            else
            {
                button1.Enabled = false;
                button2.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (i < dt.Rows.Count-1)
            {
                if (i == 0)
                {
                    button1.Enabled = true;
                }
                i++;
                pictureBox1.ImageLocation = dt.Rows[i]["picAdress"].ToString();
                lblnum.Text = dt.Rows[i]["num"].ToString();
                lblName.Text = dt.Rows[i]["name"].ToString();
                if (i == dt.Rows.Count-1)
                {
                    button2.Enabled = false;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (i == dt.Rows.Count-1)
            {
                button2.Enabled = true;
            }
            i--;
            pictureBox1.ImageLocation = dt.Rows[i]["picAdress"].ToString();
            lblnum.Text = dt.Rows[i]["num"].ToString();
            lblName.Text = dt.Rows[i]["name"].ToString();
            if (i == 0)
            {
                button1.Enabled = false;
            }
        }
    }
}

 

微信活码初实现

上一篇:使用IPVS实现Kubernetes入口流量负载均衡


下一篇:DroidVim:在安卓手机上使用vim