Cpt*_*rkt 2 c# asp.net file-type httphandler
我需要浏览器直接在浏览器中打开它能理解的文件类型(即没有"打开/保存/取消"对话框.
这是我的代码,目前效果很好!...除了每个文件弹出对话框而不直接打开文件:
string filePath = Path.Combine(WebConfigurationManager.AppSettings["NewsAttachmentPath"], context.Request.QueryString["FileName"]);
byte[] bytes = System.IO.File.ReadAllBytes(filePath);
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Expires = -1;
context.Response.Buffer = true;
context.Response.AddHeader("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "inline", context.Request.QueryString["FileName"]));
context.Response.BinaryWrite(bytes);
context.Response.End();
Run Code Online (Sandbox Code Playgroud)
如您所见,即使我将Content-Disposition更改为"inline",它仍然会提示下载.这是我知道浏览器理解的文件.换句话说,我可以访问一些随机网站并单击PDF,它将在浏览器中打开.我的网站会让我保存它以便查看它.
对"为什么要使用application/octet-stream?"的先发制人的回答?因为我不想为每种单一文件类型创建处理程序.如果这是错误的,请告诉我.
您不需要为每种文件类型创建处理程序.你只需更改一行:
context.Response.ContentType = "application/octet-stream";
Run Code Online (Sandbox Code Playgroud)
成为:
string contentType = //your logic here, possibly many lines in a separate method
context.Response.ContentType = contentType;
Run Code Online (Sandbox Code Playgroud)
但不是:你不能"内联"一个应用程序/八位字节流.这意味着"这里有一些字节,但我不知道它们是什么".除了将它保存在某个地方之外,浏览器无法做多少,因此提示下载.但是,您可以使用content-disposition建议文件名.
浏览器不适用于文件扩展名 - 它适用于内容类型.因此:您需要在响应中报告正确的内容类型.这可能意味着switch
基于您知道的文件扩展名编写/查找,或者它可能意味着将显式内容类型作为元数据与文件信息一起单独存储.
归档时间: |
|
查看次数: |
3193 次 |
最近记录: |