C# winfrom 上傳文件帶參數http Post

需求是:Java 接口http POST 接口 上傳參數  一個Text 一個File 文件類型 這個和傳輸json不同 

上代碼:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HttpPost
{
    public partial class FrmPost : Form
    {
        public FrmPost()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();//新建打開文件對話框
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);//設置初始文件目錄
            ofd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";//設置打開文件類型
            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = ofd.FileName;//FileName就是要打開的文件路徑
                textBox1.Text = FileName;                                 //下邊可以添加用戶代碼
            }
        }
        /// <summary>
        /// 上傳
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            UploadImage(textBox2.Text);
        }
              /// <summary>
              /// 通過http上傳圖片及傳參數
              /// </summary>
              /// <param name="imgPath">圖片地址(絕對路徑:D:\demo\img\123.jpg)</param>
        public void UploadImage(string imgPath)
        {
            var uploadUrl = textBox1.Text;
            //var dic = new Dictionary<string, string>() {
            //        {"para1",1.ToString() },
            //        {"para2",2.ToString() },
            //        {"para3",3.ToString() },
            //    };
            var postData = "filetype=3";//轉換成:para1=1&para2=2&para3=3
            var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
            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 = imgPath.LastIndexOf("\\");
            string fileName = imgPath.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(imgPath, 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;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            textBox3.Text = content;
        }
           
    }
}

 

就可以成功了 

主頁有json 上傳代碼 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章