19

如何从“动态”aspx 页面显示任何添加内容?目前,我正在使用 System.Web.HttpResponse“Page.Response”将存储在 Web 服务器上的文件写入 Web 请求。

这将允许人们点击http://www.foo.com?Image=test.jpg类型的 url并在他们的浏览器中显示图像。因此,您可能知道这围绕着 Response.ContentType 的使用展开。

通过使用

Response.ContentType = "application/octet-stream";

我能够显示 gif/jpeg/png 类型的图像(到目前为止我测试过的所有图像),试图显示 .swf 或 .ico 文件的尝试给了我一个不错的小错误。

使用

Response.ContentType = "application/x-shockwave-flash";

我可以播放 Flash 文件,但是图像混乱了。

那么如何轻松选择内容类型呢?

4

4 回答 4

9

这很难看,但最好的方法是查看文件并根据需要设置内容类型:

switch ( fileExtension )
{
    case "pdf": Response.ContentType = "application/pdf"; break; 
    case "swf": Response.ContentType = "application/x-shockwave-flash"; break; 

    case "gif": Response.ContentType = "image/gif"; break; 
    case "jpeg": Response.ContentType = "image/jpg"; break; 
    case "jpg": Response.ContentType = "image/jpg"; break; 
    case "png": Response.ContentType = "image/png"; break; 

    case "mp4": Response.ContentType = "video/mp4"; break; 
    case "mpeg": Response.ContentType = "video/mpeg"; break; 
    case "mov": Response.ContentType = "video/quicktime"; break; 
    case "wmv":
    case "avi": Response.ContentType = "video/x-ms-wmv"; break; 

    //and so on          

    default: Response.ContentType = "application/octet-stream"; break; 
}
于 2008-08-18T12:10:43.100 回答
0

这是我在本地 Intranet 上使用的解决方案的一部分。当我从数据库中提取它们时,您必须自己收集一些变量,但您可以从其他地方提取它们。

唯一的额外但我有一个名为getMimeType的函数,它连接到数据库并根据文件扩展名拉回正确的地雷类型。如果找不到,则默认为 application/octet-stream。

// Clear the response buffer incase there is anything already in it.
Response.Clear();
Response.Buffer = true;

// Read the original file from disk
FileStream myFileStream = new FileStream(sPath, FileMode.Open);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
myFileStream.Read(Buffer, 0, (int)FileSize);
myFileStream.Close();

// Tell the browse stuff about the file
Response.AddHeader("Content-Length", FileSize.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=" + sFilename.Replace(" ","_"));
Response.ContentType = getMimeType(sExtention, oConnection);

// Send the data to the browser
Response.BinaryWrite(Buffer);
Response.End();
于 2008-08-06T09:59:38.633 回答
0

是的,基思丑陋但真实。我最终将我们将使用的 MIME 类型放入数据库中,然后在发布文件时将它们取出。我仍然无法相信那里没有自动的类型列表,或者没有提及 MSDN 中可用的内容。

我发现这个网站提供了一些帮助。

于 2008-08-20T05:42:47.130 回答
0

由于.Net 4.5 可以使用

MimeMapping.GetMimeMapping

它返回指定文件名的 MIME 映射。

https://docs.microsoft.com/en-us/dotnet/api/system.web.mimemapping.getmimemapping

于 2017-09-25T19:47:36.700 回答