当源未实现ContentLength时,如何从另一个Web文件获取HttpWebRequest上载的responseLength以流式传输到上载中? [英] getting a responseLength for a HttpWebRequest upload from another webfile to stream into the upload when the source doesn't implement ContentLength?

查看:262
本文介绍了当源未实现ContentLength时,如何从另一个Web文件获取HttpWebRequest上载的responseLength以流式传输到上载中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景-我正在尝试使用C#中的HttpWebRequest/HttpWebResponse将现有网页流式传输到单独的Web应用程序.我要注意的一个问题是,我试图使用文件下载的content-length来设置文件上传请求的content-length,但是问题似乎出在源网页位于HttpWebResponse所不针对的Web服务器上时提供内容长度.

Background - I'm trying to stream an existing webpage to a separate web application, using HttpWebRequest/HttpWebResponse in C#. One issue I'm striking is that I'm trying to set the file upload request content-length using the file download's content-length, HOWEVER the issue seems to be when the source webpage is on a webserver for which the HttpWebResponse doesn't provide a content length.

HttpWebRequest downloadRequest = WebRequest.Create(new Uri("downloaduri")) as HttpWebRequest;
 using (HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse)
 {
   var uploadRequest = (HttpWebRequest) WebRequest.Create(new Uri("uripath"));
   uploadRequest.Method = "POST";
   uploadRequest.ContentLength = downloadResponse.ContentLength;  // ####

问题:我如何更新此方法以适应这种情况(当下载响应未设置内容长度时).也许是以某种方式使用MemoryStream吗?任何示例代码将不胜感激.

QUESTION: How could I update this approach to cater for this case (when the download response doesn't have a content-length set). Would it be to somehow use a MemoryStream perhaps? Any sample code would be appreciated.

推荐答案

如果您很乐意完全从其他Web服务器下载响应,那的确会使生活变得更轻松.从第一个Web服务器获取数据时,只需重复写入MemoryStream,然后知道为第二个请求设置的长度即可轻松写入数据(尤其是MemoryStream具有

If you're happy to download the response from the other web server completely, that would indeed make life easier. Just repeatedly write into a MemoryStream as you fetch from the first web server, then you know the length to set for the second request and you can write the data in easily (especially as MemoryStream has a WriteTo method to write its contents to another stream).

这样做的缺点是,如果文件很大,则会占用大量内存.在您的情况下,这可能会成为问题吗?替代方法包括:

The downside of this is that you'll take a lot of memory if it's a large file. Is that likely to be a problem in your situation? Alternatives include:

  • 写入文件而不是使用MemoryStream.当然,您之后需要清理文件-您基本上是将文件系统用作更大的内存:)
  • 使用分块传输编码来读取块,写入块";这个 可能是正确的-当然,这不是我以前做过的事情.
  • Writing to a file instead of using a MemoryStream. You'll need to clean up the file afterwards, of course - you're basically using the file system as bigger memory :)
  • Using a chunked transfer encoding to "read a chunk, write a chunk"; this may be fiddly to get right - it's certainly not something I've done before.

这篇关于当源未实现ContentLength时,如何从另一个Web文件获取HttpWebRequest上载的responseLength以流式传输到上载中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆