Handler (MIME) for multimedia content not working

前提是你 提交于 2019-12-23 13:56:06

问题


I am working with a handler that presents multimedia content in a page.

The idea is that this handler access the file and determine the type using the extension, and presenting it, the problem is that most of the times the handler itself gets downloaded and the multimedia is not presented.

Here is the code:

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);

The filePath variable is valid.

Could you help me avoid the handler not to present the multimedia content?


回答1:


I think I get it now, when mimeDeclaration is empty or WRONG then you don't get the image download.

This occurs in your code because mime types for images aren't always "image/" plus the file extension:

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

Eg for a .jpg image it's

image/jpeg

Otherwise it's probably because it's a tiff image in that case your else clause is setting mimeDeclaration back to an empty string.

Tip: detecting MIME types by file extension is less than ideal, check the way I do it here: Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types



来源:https://stackoverflow.com/questions/31588006/handler-mime-for-multimedia-content-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!