zoukankan      html  css  js  c++  java
  • 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 + "
    ");
    
    
        // 文件参数头              
        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}"
    Content-Type: application/octet-stream
    
    ");
    
            // 开始拼数据
            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($"
    ");
            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($"
    --{boundary}
    Content-Disposition: form-data; name="{name}"
    
    {value}
    ");
        //    memStream.Write(bytes, 0, bytes.Length);
        //}
    
    
        // 写入最后的结束边界符            
        var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--
    ");// 最后的结束符
        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;
                }
            }
        }
  • 相关阅读:
    swift4.2
    swift4.2 打印devicetoken
    swift4.2
    (二十三)Dbutils 工具介绍
    (二十二)自定义简化版JDBC(Dbutils框架的设计思想)
    (二十一)配置三种开源数据库连接池
    (二十)自定义数据库连接池
    (十九)事务
    (十八)JDBC获取存储过程和主键
    (十七)使用JDBC进行批处理
  • 原文地址:https://www.cnblogs.com/guxingy/p/9448649.html
Copyright © 2011-2022 走看看