Using HttpWebRequest to send POST data C# (使用HttpWebRequest 上传文件)

Hi, try this solution. I have used it to upload files to a php Web shop. Any questions – better contact me directly – anefedov(a – t )list(dot)ru Sorry for silly antispan protection public override int uploadArticles() { try { WebRequest webRequest; WebResponse webResponse; DirectoryInfo di = new DirectoryInfo(getStoragePath(WebShopBrokerStatuses.PATH_STORAGE_ARTICLES)); FileInfo[] filist = di.GetFiles(); for (int ix = 0; ix < filist.Length; ix++) { webRequest = WebRequest.Create(OscUrl + “admin/easypopulate.php?split=0”); webRequest.Method = WebRequestMethods.Http.Post; webRequest.Headers.Add(“Cookie”, “osCAdminID=” + oscAdmCookie); webRequest.Headers.Add(“Accept”, “image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-shockwave-flash, */*”); webRequest.Headers.Add(“Referer”, “http://localhost/OSC/admin/easypopulate.php”); webRequest.Headers.Add(“Accept-Language”, “ru”); string boundary = “—————————” + DateTime.Now.Ticks.ToString().Substring(0, 11); webRequest.ContentType = “multipart/form-data; boundary=” + boundary; StringBuilder content = new StringBuilder(); content.AppendLine(boundary); content.AppendLine(“Content-Disposition: form-data; name=”MAX_FILE_SIZE””); content.AppendLine(“”); content.AppendLine(“100000000”); content.AppendLine(boundary); content.AppendLine(“Content-Disposition: form-data; name=”usrfl”; filename=””+filist[ix].FullName+”””); content.AppendLine(“Content-Type: application/vnd.ms-excel”); content.AppendLine(“”); String fileContent = filist[ix].OpenText().ReadToEnd(); content.AppendLine(fileContent); content.AppendLine(boundary); content.AppendLine(“Content-Disposition: form-data; name=”imput_mode””); content.AppendLine(“”); content.AppendLine(“normal”); content.AppendLine(boundary); content.AppendLine(“Content-Disposition: form-data; name=”buttoninsert””); content.AppendLine(“”); content.AppendLine(“Insert into db”); content.AppendLine(boundary+”–“); byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(content.ToString()); webRequest.ContentLength = data.Length; System.IO.Stream os = webRequest.GetRequestStream(); os.Write(data, 0, data.Length); os.Close(); /*FileInfo fi = new FileInfo(“request.txt”); FileStream fs = fi.OpenWrite(); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close();*/ webResponse = webRequest.GetResponse(); } } catch (Exception e) { return WebShopBrokerStatuses.ERROR_UPLOAD_ARTICLES; } return WebShopBrokerStatuses.SUCESS; }

引文来源  Using HttpWebRequest to send POST data C# .NET