Reading Image from Web Server in C# proxy(在 C# 代理中从 Web 服务器读取图像)
问题描述
我正在尝试编写一个代理,该代理从一台服务器读取图像并将其返回给提供的 HttpContext,但我只是获取了字符流.
I am trying to write a proxy which reads an image from one server and returns it to the HttpContext supplied, but I am just getting character stream back.
我正在尝试以下操作:
WebRequest req = WebRequest.Create(image);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter (context.Response.OutputStream);
sw.Write (sr.ReadToEnd());
但正如我之前提到的,这只是用文字回应.
But as I mentioned earlier, this is just responding with text.
我如何告诉它它是一个图像?
How do I tell it that it is an image?
我从一个网页中的 img 标签的 source 属性中访问它.将内容类型设置为 application/octet-stream 提示保存文件并将其设置为 image/jpeg 仅以文件名响应.我想要的是调用页面返回并显示的图像.
I am accessing this from within a web page in the source attribute of an img tag. Setting the content type to application/octet-stream prompts to save the file and setting it to image/jpeg just responds with the filename. What I want is the image to be returned and displayed by the calling page.
推荐答案
既然你在使用二进制,你就不想使用 StreamReader,它是一个 Text读者!
Since you are working with binary, you don't want to use StreamReader, which is a TextReader!
现在,假设您已正确设置内容类型,您应该只使用响应流:
Now, assuming that you've set the content-type correctly, you should just use the response stream:
const int BUFFER_SIZE = 1024 * 1024;
var req = WebRequest.Create(imageUrl);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
var bytes = new byte[BUFFER_SIZE];
while (true)
{
var n = stream.Read(bytes, 0, BUFFER_SIZE);
if (n == 0)
{
break;
}
context.Response.OutputStream.Write(bytes, 0, n);
}
}
}
这篇关于在 C# 代理中从 Web 服务器读取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 代理中从 Web 服务器读取图像
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 使用 rss + c# 2022-01-01
