模拟浏览器多文件上传

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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。