码迷,mamicode.com
首页 > Web开发 > 详细

模拟浏览器多文件上传

时间:2014-11-19 18:20:15      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

string responseStr = null; 
            string boundary = "----------------------" + DateTime.Now.Ticks.ToString("x"); 
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("目标服务器地址");
            request.Method = "POST";
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.KeepAlive = true; 
            request.Timeout = 95000;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36";
            
            System.IO.Stream rs = request.GetRequestStream();
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";   
            for (int k = 0; k < Request.Files.Count; k++)
            {
                System.Web.HttpPostedFile hp = Request.Files[k];
                string filename = hp.FileName;
                //文件分隔符
                rs.Write(boundarybytes, 0, boundarybytes.Length); 
                //文件头 
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(string.Format(headerTemplate,"file"+k, filename,hp.ContentType));
                rs.Write(headerbytes, 0, headerbytes.Length);
                headerbytes = new byte[hp.InputStream.Length];
                //文件数据
                hp.InputStream.Read(headerbytes,0,headerbytes.Length);
                rs.Write(headerbytes, 0, headerbytes.Length); 
            }
            //结束分隔符
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close(); 
            WebResponse wresp = null;
            try
            {
                wresp = request.GetResponse();
                System.IO.Stream stream2 = wresp.GetResponseStream();
                System.IO.StreamReader reader2 = new System.IO.StreamReader(stream2);
                responseStr = reader2.ReadToEnd(); 
            }
            catch
            { 
            }
            finally
            {
                request = null;
            } 
            Response.Write(responseStr); ;

 

模拟浏览器多文件上传

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/you000/p/4108611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!