C# 類比多檔案上傳

來源:互聯網
上載者:User

標籤:files   box   ESS   換行   method   www.   arp   adf   cte   

原地址:http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html

 

1、用戶端代碼 用winform寫的

private void button1_Click(object sender, EventArgs e){    string postURL = "http://localhost:40694/test1/Handler1.ashx";    string[] files = { "F:\\1.png", "F:\\2.png" };    string str = HttpUploadFile(postURL, files);    MessageBox.Show(str);}public string HttpUploadFile(string url, string[] files){    //HttpContext context    //參考http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html    var memStream = new MemoryStream();    // 邊界符    var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");    var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");    // 檔案參數頭                  foreach (var item in files)    {        string filePath = item;        string fileName = Path.GetFileName(item);        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);        var fileHeaderBytes = Encoding.UTF8.GetBytes($"Content-Disposition: form-data; name=\"{"file"}\"; filename=\"{fileName}\"\r\nContent-Type: application/octet-stream\r\n\r\n");        // 開始拼資料        memStream.Write(beginBoundary, 0, beginBoundary.Length);        // 檔案資料        memStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);        var buffer = new byte[1024];        int bytesRead;        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)        {            memStream.Write(buffer, 0, bytesRead);        }        fileStream.Close();        //必須得寫入一個換行        byte[] bytes = Encoding.UTF8.GetBytes($"\r\n");        memStream.Write(bytes, 0, bytes.Length);    }    //// Key-Value資料                //Dictionary<string, string> stringDict = new Dictionary<string, string>();    //stringDict.Add("len", "500");    //stringDict.Add("wid", "300");    //stringDict.Add("test1", "1");    //foreach (var item in stringDict)    //{    //    string name = item.Key;    //    string value = item.Value;    //    byte[] bytes = Encoding.UTF8.GetBytes($"\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n");    //    memStream.Write(bytes, 0, bytes.Length);    //}    // 寫入最後的結束邊界符                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");// 最後的結束符    memStream.Write(endBoundary, 0, endBoundary.Length);    //寫入到tempBuffer    memStream.Position = 0;    var tempBuffer = new byte[memStream.Length];    memStream.Read(tempBuffer, 0, tempBuffer.Length);    memStream.Close();    // 建立webRequest並設定屬性    var webRequest = (HttpWebRequest)WebRequest.Create(url);    webRequest.Method = "POST";    webRequest.Timeout = 100000;    webRequest.ContentType = "multipart/form-data; boundary=" + boundary;    webRequest.ContentLength = tempBuffer.Length;    var requestStream = webRequest.GetRequestStream();    requestStream.Write(tempBuffer, 0, tempBuffer.Length);    requestStream.Close();    var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();    string responseContent;    using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))    {        responseContent = httpStreamReader.ReadToEnd();    }    httpWebResponse.Close();    webRequest.Abort();    return responseContent;}

2、服務端代碼

 public class Handler1 : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string strFileNames = "";            if (context.Request.Files.Count > 0)            {                for (int i = 0; i < context.Request.Files.Count; i++)                {                    HttpPostedFile _HttpPostedFile = context.Request.Files[i];                    strFileNames += _HttpPostedFile.FileName + ",";                    _HttpPostedFile.SaveAs(context.Server.MapPath($"./{_HttpPostedFile.FileName}"));                }                //context.Response.Write($"files:{context.Request.Files.Count}  filenames:{strFileNames}");            }            //context.Response.Write(context.Request.Form["len"]);            //context.Response.Write(JsonConvert.SerializeObject(context.Request.Form.AllKeys.Length.ToString()));            context.Response.Write(strFileNames);        }        public bool IsReusable        {            get            {                return false;            }        }    }

 

C# 類比多檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.