我正在嘗試寫一個接受圖像的http服務器。我設法通過這種方式傳輸txt文件或簡單文本。但是,當涉及到JPEG文件,被轉移的人變得無法訪問。通過http發送jpg文件
客戶端:
WebRequest request = WebRequest.Create("http://localhost:8080");
request.Method = "POST";
byte[] byteArray = System.IO.File.ReadAllBytes(path);
request.ContentType = "image/jpeg";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
服務器端:
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
StreamReader reader = new StreamReader(request.InputStream,request.ContentEncoding);
Console.WriteLine("Client data content type {0}", request.ContentType);
String Data = reader.ReadToEnd();
byte[] imagebuffer = System.Text.Encoding.UTF8.GetBytes(Data);
System.IO.File.WriteAllBytes(path, imagebuffer);
當我嘗試這與.txt文件,字節數組的每邊長不改變和服務器端文件可讀。但使用jpg,數組長度是不同的。我想這是造成這個問題。我能做些什麼來避免這種情況?還是有其他選擇嗎?
編輯:用「BinaryReader」替換「StreamReader」,現在工作正常。好像;
BinaryReader reader = new BinaryReader(request.InputStream, request.ContentEncoding);
byte[] imagebuffer = reader.ReadBytes((int)request.ContentLength64);
System.IO.File.WriteAllBytes(path, imagebuffer);
[「John Saunders編輯了你的標題,請參閱」應該在標題中包含「標籤嗎?」,其中的共識是「不,他們不應該」。/questions/15214204/return-different-lists-for-each-key#comment21443674_15214204) – 2013-03-05 02:47:52