1. 程式人生 > >c# http協議上傳檔案+傳輸數資料

c# http協議上傳檔案+傳輸數資料

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication2.selectSDF.http
{
    class Uploadzip
    {
        static void Main(string[] args) {
            string Upload_Url = "http://device.js.cn/rest?method=zh,grabbinglog";
            int timeOut = 30000;
            string ZipedFile= "D:/Project/啟動檔案.jpg";

            Dictionary<string, string> myCol = new Dictionary<string, string>();
            myCol.Add("00000000", "xxxxxxxx");
            myCol.Add("commandId", "xxxxx");
            myCol.Add("deviceSn",  "xxxxxxxx");

            //檔案地址,響應時間,file,檔案路徑,傳輸資料
            HttpPostData(Upload_Url, timeOut, "file", ZipedFile, myCol);             
        }

        /// <summary>
        ///   檔案上傳及資料傳輸
        /// </summary>
        /// <param name="url"> 訪問的伺服器地址及介面</param>
        /// <param name="timeOut">設定請求超時時間</param>
        /// <param name="fileKeyName">file</param>
        /// <param name="filePath">檔案上傳的本地路徑</param>
        /// <param name="list">傳輸的json資料</param>
        /// <returns></returns>
        public static string HttpPostData(string url, int timeOut, string fileKeyName, string filePath, Dictionary<string, string> list) 
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 邊界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 邊界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最後的結束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 設定屬性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 寫入檔案----------1.--------------
            string filename = filePath.Substring(filePath.LastIndexOf("/")+ 1);
             string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=" + filename + "\r\n" + "Content-Type: application/octet-stream\r\n\r\n";                 
            var header = string.Format(filePartHeader, fileKeyName, filePath);

            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
 
            string stringKeyHeader = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";     
            foreach (var item in list)
            {   //----------- 傳輸資料的編碼集。
                var dataByte = Encoding.UTF8.GetBytes(string.Format(stringKeyHeader, item.Key, item.Value));
                memStream.Write(dataByte, 0, dataByte.Length);//迴圈寫入 引數  
            }             

            // 寫入最後的結束邊界符------------ 3.-------------------------
            memStream.Write(endBoundary, 0, endBoundary.Length);

            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();

            //響應 ------------------- 4.-----------------------------------
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")) )
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }
    }

}