2014-04-14 1 views
0

이미지를 (jpeg 포맷으로) 서버에 업로드하려고했습니다. 몇 가지 접근 방식을 사용했지만 그 중 아무 것도 작동하지 않았습니다.httpwebrequest를 사용하여 jpeg로 인코딩 된 비트 맵을 서버에 업로드하십시오.

접근 방식은 1

내가 직접 HttpWebRequest 스트림에 JPEG 데이터를 저장 시도했다 :

//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으로 테스트 할 때, 완벽한 이미지가 만들어졌습니다.

나는 또한 MemoryStream로하고 HttpWebRequest 스트림에 복사하는 것보다 JPEG 데이터를 저장하는 노력이

접근 방식 :

//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

두 번째 접근 방법에서 [Stream.CopyTo] (http://msdn.microsoft.com/en-us/library/dd782932.aspx)를 사용하면 어떻게됩니까? 예를 들어 ms.CopyTo (s); – Clemens

+0

그리고 어떤 종류의 서버가'http : // localhost'에서 듣고 있습니까? – Clemens

+0

@Clemens : .NET 3.0에는 Stream.CopyTo 기능이 없습니다. – JMRC

답변

1

삽입이 당신의 while 루프 전에 :

ms->Seek(0, SeekOrigin.Begin); 

문제는 당신이 스트림의 끝에서 당신의 읽기 시작입니다 ... DOH!

+0

네, 그렇게 똑똑하지 않았습니다. 'ms-> Position = 0;'을 삽입하는 것을 잊었지만 이번에는'ProtocolViolationException'을 던졌습니다. 이제 어떻게 해결할 수 있는지 알아 내려고 노력 중입니다. – JMRC

관련 문제