C#如何设置响应头,让浏览器在线查看图片而不是下载?
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
核心:两个响应头浏览器决定"下载"还是"在线显示",看的是:
图片走 // 在你的 ProcessRequest 中,校验通过后: var fi = new FileInfo(physical); string ext = fi.Extension.ToLowerInvariant(); string mime; bool inline = false; switch (ext) { case ".png": mime = "image/png"; inline = true; break; case ".jpg": case ".jpeg": mime = "image/jpeg"; inline = true; break; case ".gif": mime = "image/gif"; inline = true; break; case ".webp": mime = "image/webp"; inline = true; break; // .svg 保持 attachment,防止 XSS default: mime = "application/octet-stream"; break; } resp.ContentType = mime; resp.AddHeader("Content-Disposition", (inline ? "inline" : "attachment") + "; filename=\"" + Uri.EscapeDataString(fi.Name) + "\""); resp.AddHeader("Content-Length", fi.Length.ToString()); // 必须手动设置 // 如果处理器不需要 Session,不要实现 IRequireSessionState // 如果需要只读 Session,实现 IReadOnlySessionState resp.TransmitFile(physical); // 一行完成,零内存缓冲 该文章在 2026/12/1 11:35:41 编辑过 |
关键字查询
相关文章
正在查询... |