c# – 处理程序(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图像,它是

image/jpeg

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

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

点赞