我的代码想要将图片上传到服务器,如下所示,但它总是失败。你知道为什么吗?
public static void SendRequest(System.Text.StringBuilder sReq, byte[] sbyteData, Action<UpLoadPicData, int> onEventResponse = null, Action onFinally = null)
{
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri u = new Uri(sReq.ToString());
wc.Headers[HttpRequestHeader.ContentLength] = sReq.Length.ToString();
wc.Headers[HttpRequestHeader.Accept] = "*/*";
wc.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
wc.OpenWriteAsync(u, "POST", sbyteData);
}
public static void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Error == null)
{
object[] objArr = e.UserState as object[];
byte[] fileContent = e.UserState as byte[];
Stream outputStream = e.Result;
outputStream.Write(fileContent, 0, fileContent.Length);
outputStream.Flush();
outputStream.Close();
}
}
答案 0 :(得分:3)
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
image1.Source = bmp;
byte[] sbytedata = ReadToEnd(e.ChosenPhoto);
string s = sbytedata.ToString();
WebClient wc = new WebClient();
Uri u = new Uri("url here");
wc.OpenWriteCompleted+=new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
wc.OpenWriteAsync(u, "POST", sbytedata);
}
}
public static void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (e.Error == null)
{
object[] objArr = e.UserState as object[];
byte[] fileContent = e.UserState as byte[];
Stream outputStream = e.Result;
outputStream.Write(fileContent, 0, fileContent.Length);
outputStream.Flush();
outputStream.Close();
string s = e.Result.ToString(); ;
}
}
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
我使用了你的代码...而且它工作了..我还将转换为byte []从图像源到此..图像来自图库
答案 1 :(得分:1)
使用WebClient
执行此操作将非常棘手(我不确定它是否可能)在手机上。请改用HttpWebRequest
。
查看关于同一主题的其他问题:
Uploading an image using C# and WebRequest?
和
Upload files with HTTPWebrequest (multipart/form-data)