0
首先,我的服务器是一个自托管的c#web服务。它适用于我的其他应用程序,但现在我必须在其中实现一个方法,该方法将由具有Windows CE 5的移动计算机使用。我需要在我的服务器中接收文件,因此我编写了此方法:C#:尝试使用httpwebrequest发送文件到自托管web服务的错误
[System.ServiceModel.OperationContract, WebInvoke(UriTemplate = "test/")]
string testSaveFile(Stream arq);
public string testSaveFile(Stream img) {
Console.WriteLine("stream received");
Console.WriteLine("stream size: " + img.Length); //throws "Error 400 Bad Request"
}
和移动电脑,使用的.Net CF 3.5,我写这个方法来发送文件:
public static string UploadFilesToRemoteUrl(string url, string file) {
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest2.AllowWriteStreamBuffering = true;
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--"
+ boundary + "\r\n");
memStream.Write(boundarybytes, 0, boundarybytes.Length);
length += boundarybytes.Length;
string headerTemplate = "Content-Disposition: form-data; name=\"file\";"
+" filename=\"file\"\r\n Content-Type: \"application/octet-stream\"\r\n\r\n";
string header = headerTemplate;
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
length += headerbytes.Length;
FileStream fileStream = new FileStream(file, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
memStream.Write(buffer, 0, bytesRead);
length += bytesRead;
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
length += boundarybytes.Length;
fileStream.Close();
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
//^Exception here
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string res = reader2.ReadToEnd();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
return res;
}
而且使用这种方法我能够连接到服务器。它甚至显示第一条消息(“流接收”)。但每当我尝试访问流时,服务器都会返回“错误400错误请求”,这在移动计算机上显示为例外。 那么我怎样才能从移动电脑发送文件到服务器?我可以修复这种方法,还是应该尝试另一种方法?
this question的答案说异步执行它,但我做到了,并且返回了相同的错误,并且同一个服务器由Android应用程序使用,它可以同步执行并且可以工作。
在此先感谢。
还有一件事:multipart/form-data是将文件发送到此webmethod的正确方法吗?