我一直试图将图片(jpeg格式化)上传到服务器。我使用了一些不同的方法,但没有一种方法有效。
APPROACH 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测试时,创建了一个完美的图像。
APPROACH 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();
有人可以告诉我我做错了什么或者给我一个替代方案吗?
谢谢。
答案 0 :(得分:1)
在你的while循环之前插入它:
ms->Seek(0, SeekOrigin.Begin);
问题是你是从流的末尾开始阅读... doh!