1

每个人。我正在使用 c# 语言进行编程,但我遇到了 WebClient 类的问题。我使用 WebClient.DownloadData 方法下载了一张图片,效果很好。但是,WebClient.UploadData 没有。详细地说,我有一个 byte[] 包含一个图像的内容 - 命名为字节,以及一个我要上传到的图像文件夹的 URL - 命名为 filePath。然后,

 WebClient wc = new WebClient(); 
 byte[] responseArray = wc.UploadData(filePath, "POST", bytes);

并在出现错误后返回给我

System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
   at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
   at System.Net.WebClient.UploadData(String address, String method, Byte[] data)

我还研究了一些解决这个问题的方法,但是没有一个对我有用。:(请帮忙!:-s

4

1 回答 1

2

试试这个页面。它有一个发布示例。

它使用 webrequest 而不是 webclient,但它来自微软,应该是一个很好的例子。

WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;


//Here is the Business end of the code...
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
//and here is the response.
WebResponse response = request.GetResponse ();

Console.WriteLine (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();

我精简了代码并评论了您要查看的部分。

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

于 2011-04-14T03:40:32.973 回答