C# 模拟多文件上传

原地址: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;
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/guxingy/p/9448649.html