2008-08-06 40 views
12

如何顯示來自「動態」aspx頁面的任何添加內容?目前,我正在使用System.Web.HttpResponse「Page.Response」將存儲在Web服務器上的文件寫入Web請求。顯示來自Respose.WriteFile()/ Response.ContentType的廣告內容

這將允許用戶點擊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文件播放,但隨後的圖像混亂。

那麼我如何容易選擇contenttype?

回答

8

這是醜陋的,但最好的方法是看該文件,內容類型設置爲合適的:

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; 
} 
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(); 
0

Keith醜陋,但卻是事實。我最終將我們將使用的MIME類型放入數據庫,然後在我發佈文件時將其拉出。我仍然無法相信那裏沒有任何類型的自動列表,也沒有提及MSDN中可用的內容。

我發現this網站提供了一些幫助。