在 C# 代理中从 Web 服务器读取图像
- 作者: 朕就静静的看你装逼
- 来源: 51数据库
- 2023-02-13
问题描述
我正在尝试编写一个代理,该代理从一台服务器读取图像并将其返回给提供的 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源