【问题标题】:Upload jpeg encoded bitmap to server with httpwebrequest使用 httpwebrequest 将 jpeg 编码的位图上传到服务器
【发布时间】: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-&gt;ContentLength = ms-&gt;Length;

标签: wpf bitmap httpwebrequest .net-3.0


【解决方案1】:

在你的 while 循环之前插入:

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

问题是您是从流的末尾开始阅读的... doh!

【讨论】:

  • 是的,这不是很聪明。我忘了插入ms-&gt;Position = 0;,但这次它抛出了ProtocolViolationException。现在我正在想办法解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多