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

Handler (MIME) for multimedia content not working

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

这个想法是这个处理程序访问文件并使用扩展名确定类型,并呈现它,问题是大多数时候 处理程序本身已下载,但未显示多媒体。

代码如下:

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 图像,它是

image/jpeg

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

提示:通过文件扩展名检测 MIME 类型不太理想,请查看我在此处执行此操作的方式:Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types