I've been trying to upload an image (jpeg formatted) to the server. I've used some different approaches, but none of them worked.
APPROACH 1
I've tried saving the jpeg data directly to HttpWebRequest
stream:
//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();
Writing to the HttpWebRequest
stream doesn't work, but when I tested it with FileStream, a perfect image was created.
APPROACH 2
I also tried saving the jpeg data to a MemoryStream
and than copying it to the HttpWebRequest
stream:
//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();
Can someone tell me what I'm doing wrong or give me an alternative?
Thank you.