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 服务器读取图像
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
