将二进制数据从C#上传到PHP

我想将文件从Windows C#应用程序上传到运行PHP的Web服务器。

我知道WebClient.UploadFile方法,但我希望能够以块的forms上传文件,以便我可以监视进度并能够暂停/恢复。

因此,我正在阅读文件的一部分并使用WebClient.UploadData方法。

我遇到的问题是我不知道如何访问从UploadData发送的数据。 如果我对post数据执行print_r,我可以看到有二进制数据,但我不知道访问它的密钥。 如何访问二进制数据? 有没有更好的方法我应该完全这样做?

String file = "C:\\Users\\Public\\uploadtest\\4.wmv"; using (BinaryReader b = new BinaryReader(File.Open(file, FileMode.Open))) { int pos = 0; int required = 102400; b.BaseStream.Seek(pos, SeekOrigin.Begin); byte[] by = b.ReadBytes(required); using (WebClient wc = new WebClient()){ wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] result = wc.UploadData("http://192.168.0.52/html/application.php", "POST", by); String s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length); MessageBox.Show(s); } } 

在此处输入图像描述

这就是我进行HTTP通信的方式。

我想当我到达using() ,正在建立HTTP连接,并且在using() {...}体内你可以做暂停和填充。

 string valueString = "..."; string uriString = "http://someUrl/somePath"; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uriString); httpWebRequest.Method = "POST"; string postData = "key=" + Uri.EscapeDataString(valueString); byte[] byteArray = Encoding.UTF8.GetBytes(postData); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = byteArray.Length; using (Stream dataStream = httpWebRequest.GetRequestStream()) { // do pausing and stuff here by using a while loop and changing byteArray.Length into the desired length of your chunks dataStream.Write(byteArray, 0, byteArray.Length); } HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream receiveStream = httpWebResponse.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream); string internalResponseString = readStream.ReadToEnd(); 

但是在上传文件时,您应该使用multipart/form-data而不是application/x-www-form-urlencoded 。 另见: http : //www.php.net/manual/en/features.file-upload.post-method.php

在php中,您可以使用超全局变量$ _FILES(例如print_r($_FILES); )来访问上传的文件。

并且还阅读: https : //stackoverflow.com/a/20000831/1209443 ,了解有关如何处理multipart/form-data更多信息

用这个。 这肯定会起作用。 System.Net.WebClient Client = new System.Net.WebClient();

  Client.Headers.Add("Content-Type", "binary/octet-stream"); byte[] result = Client.UploadFile("http://192.168.0.52/mipzy/html/application.php", "POST", file); string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length); MessageBox.Show(s); 

或者使用的那个

 using (System.Net.WebClient Client = new System.Net.WebClient()) { Client.Headers.Add("Content-Type", "binary/octet-stream"); byte[] result = Client.UploadFile("http://192.168.0.52/mipzy/html/application.php", "POST", file); string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length); MessageBox.Show(s); } 

没有二元阅读器。 如果您需要二进制阅读器,还必须为表单提供一些多部分参数。 这是由UploadFile事件自动完成的。