显示来自Respose.WriteFile()/ Response.ContentType的广告内容

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

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

通过使用

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

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

运用

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

我可以播放Flash文件,但随后图像混乱。

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

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

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

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

唯一的额外function,但我有一个名为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(); 

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

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

由于.Net 4.5可以使用

 MimeMapping.GetMimeMapping 

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

https://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping(v=vs.110).aspx