C# http 模拟 from 表单提交 文件及其数据

it2022-05-05  120

   /// <summary>         /// 上传的方法         /// </summary>         /// <param name="uploadfile">单个文件名(上传多个文件的方法自己修改)</param>         /// <param name="url">post请求的url</param>         /// <param name="poststring">post的字符串 键值对,相当于表单上的文本框里的字符</param>         /// <returns></returns>         public static string UploadFileEx(string uploadfile, string url, NameValueCollection poststring)         {             Uri uri = new Uri(url);

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");             HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);             webrequest.ContentType = "multipart/form-data; boundary=" + boundary;             webrequest.Method = "POST";

            // Build up the post message header              StringBuilder sb = new StringBuilder();

            //加文本             foreach (string key in poststring.Keys)             {                 sb.Append("--");                 sb.Append(boundary);                 sb.Append("\r\n");                 sb.Append("Content-Disposition: form-data; name=\"");                 sb.Append(key);                 sb.Append("\"");                 sb.Append("\r\n");                 sb.Append("\r\n");                 sb.Append(poststring.Get(key));                 sb.Append("\r\n");             }

            //加文件             sb.Append("--");             sb.Append(boundary);             sb.Append("\r\n");             sb.Append("Content-Disposition: form-data; name=\"filename\";");             sb.Append("filename=\"");             sb.Append(Path.GetFileName(uploadfile));             sb.Append("\"");             sb.Append("\r\n");             sb.Append("Content-Type: multipart/form-data");             sb.Append("\r\n");             sb.Append("\r\n");

            string postHeader = sb.ToString();             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

            // Build the trailing boundary string as a byte array              // ensuring the boundary appears on a line by itself              byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);             long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;             webrequest.ContentLength = length;

            Stream requestStream = webrequest.GetRequestStream();

            // Write out our post header              requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Write out the file contents              byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];             int bytesRead = 0;             while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)                 requestStream.Write(buffer, 0, bytesRead);

            // Write out the trailing boundary              requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

            webrequest.Timeout = 1000000;

            //System.Windows.Forms.MessageBox.Show(webrequest.Timeout.ToString()); 

            WebResponse responce = webrequest.GetResponse();

            Stream s = responce.GetResponseStream();

            StreamReader sr = new StreamReader(s);

            string str = sr.ReadToEnd();

            fileStream.Close();

            requestStream.Close();

            sr.Close();

            s.Close();

            responce.Close();

            return str;         }

 

 

 

调用:

        static void Main(string[] args)         {

            NameValueCollection poststring = new NameValueCollection();

            poststring["username"] = "laokaizzz";//post 的参数    poststring["password"] = "111111111";                string uploadfile;// set to file to upload             string uploadfile = @"E:\图片\123.jpg";//上传的文件名

            string str = UploadFileEx(uploadfile, "http://localhost:61729/data.aspx", poststring); 

        }

 

http数据请求接口 服务端

  protected void Page_Load(object sender, EventArgs e)         {             string username = Request["username"];             for (int i = 0; i < Request.Files.Count; i++)             {                 HttpPostedFile img = Request.Files[i];                 string s = img.FileName;             }

        }


最新回复(0)