Respose.WriteFile()/Response.ContentType からの広告コンテンツの表示
-
08-06-2019 - |
質問
「動的」aspx ページから追加コンテンツを表示するにはどうすればよいでしょうか?現在、System.Web.HttpResponse "Page.Response" を使用して、Web サーバーに保存されているファイルを Web リクエストに書き込むことに取り組んでいます。
これにより、人々はそのタイプへの URL をヒットできるようになります。 http://www.foo.com?Image=test.jpg ブラウザに画像を表示させます。ご存知のとおり、これは 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;
}
他のヒント
これは、私がローカル イントラネットで使用しているソリューションの一部です。一部の変数はデータベースから取得するため、自分で収集する必要がありますが、他の場所から取得することもできます。
唯一の追加機能として、次の関数があります。 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();
.Net 4.5以降は使用できます
MimeMapping.GetMimeMapping
指定されたファイル名の MIME マッピングを返します。
https://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping(v=vs.110).aspx