【发布时间】:2014-05-28 19:31:15
【问题描述】:
我一直在尝试将图像(jpeg 格式)上传到服务器。我使用了一些不同的方法,但都没有奏效。
方法 1
我尝试将 jpeg 数据直接保存到HttpWebRequest 流:
//Create bitmap.
BitmapImage^ bm = gcnew BitmapImage(gcnew Uri(PATH, UriKind::Relative));
/*
Do stuff with bitmap.
*/
//Create the jpeg.
JpegBitmapEncoder enc;
enc.Frames->Add(BitmapFrame::Create(bm));
//Prepare the web request.
HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(L"http://localhost"));
request->ContentType = "image/jpeg";
request->Method = "PUT";
//Prepare the web request content.
Stream^ s = request->GetRequestStream();
enc.Save(s);//Throws 'System.NotSupportedException'.
s->Close();
写入HttpWebRequest 流不起作用,但是当我使用 FileStream 对其进行测试时,创建了一个完美的图像。
方法 2
我还尝试将 jpeg 数据保存到 MemoryStream,而不是将其复制到 HttpWebRequest 流:
//Create bitmap.
BitmapImage^ bm = gcnew BitmapImage(gcnew Uri(PATH, UriKind::Relative));
/*
Do stuff with bitmap.
*/
//Create the jpeg.
MemoryStream^ ms = gcnew MemoryStream;
JpegBitmapEncoder enc;
enc.Frames->Add(BitmapFrame::Create(bm));
enc.Save(ms);
//Prepare the web request.
HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(L"http://localhost"));
request->ContentType = "image/jpeg";
request->Method = "PUT";
//Prepare the web request content.
Stream^ s = request->GetRequestStream();
int read;
array<Byte>^ buffer = gcnew array<Byte>(10000);
while((read = ms->Read(buffer, 0, buffer->Length)) > 0)//Doesn't read any bytes.
s->Write(buffer, 0, read);
s->Close();
ms->Close();
谁能告诉我我做错了什么或给我一个替代方案?
谢谢。
【问题讨论】:
-
如果您在第二种方法中使用Stream.CopyTo 会怎样,例如
ms.CopyTo(s);? -
在
http://localhost监听的是什么服务器? -
@Clemens:.Net 3.0 没有 Stream.CopyTo 函数。
-
@Clemens:这只是一个测试
index.php,显示请求的内容和请求方法。如果我将二进制数组分配给ms,而不是保存JPEG编码数据,请求和响应确实可以正常工作,所以我认为链接没有问题。 -
您也可以尝试设置
request->ContentLength = ms->Length;。
标签: wpf bitmap httpwebrequest .net-3.0