用于多媒体内容的处理程序(MIME)不起作用

我正在使用一个在页面中呈现多媒体内容的处理程序。

这个想法是这个处理程序访问文件并使用扩展来确定类型,并且呈现它, 问题在于处理程序本身被下载并且多媒体没有被呈现的大多数时候。

这是代码:

FileInfo file = new FileInfo(filePath); byte[] bytes = new byte[file.Length]; using (FileStream fs = file.OpenRead()) { fs.Read(bytes, 0, bytes.Length); } string extension = Path.GetExtension(filePath); string mimeDeclaration; if (".tif" == extension) mimeDeclaration = "tiff"; string[] imagenes = new string[] {".jpg", ".jpeg", ".bmp", ".gif", ".png"}; if (imagenes.Any(x => x.Contains(extension))) mimeDeclaration = extension.Substring(1); else mimeDeclaration = string.Empty; context.Response.ClearContent(); context.Response.ClearHeaders(); context.Response.ContentType = "image/" + mimeDeclaration; context.Response.BinaryWrite(bytes); 

filePath变量有效。

你能帮我避免处理程序不提供多媒体内容吗?

我想我现在得到它,当mimeDeclaration为空或错误然后你没有得到图像下载。

这在代码中会发生,因为图像的mime类型并不总是 “image /”加上文件扩展名:

 context.Response.ContentType = "image/" + mimeDeclaration; 

例如,对于.jpg图像,它是

图像/ JPEG

否则它可能是因为它是一个tiff图像,在这种情况下你的else子句将mimeDeclaration设置回一个空字符串。

提示:通过文件扩展名检测MIME类型不太理想,请查看我在此处执行的方式: Urlmon.dll中FindMimeFromData方法的替代方法,其中包含更多MIME类型