我一直在尝试将图像(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();
有人能告诉我我做错了什么吗?或者给我一个替代方案?
谢谢。
在while循环之前插入这个:
ms->Seek(0, SeekOrigin.Begin);
问题是你是从流的末尾开始阅读的。。。doh!