عرض محتوى الإعلان من Respose.WriteFile()/ Response.ContentType
-
08-06-2019 - |
سؤال
كيف يمكن عرض أي محتوى إضافة من صفحة ASPX "ديناميكية"؟أعمل حاليًا على استخدام System.Web.HttpResponse "Page.Response" لكتابة ملف مخزن على خادم ويب لطلب ويب.
سيسمح هذا للأشخاص بضرب عنوان 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";
يمكنني الحصول على ملفات فلاش لتشغيلها، لكن الصور تفسد بعد ذلك.
فكيف أفعل بسهولة اختيار نوع المحتوى؟
المحلول
هذا أمر قبيح، ولكن أفضل طريقة هي النظر إلى الملف وتعيين نوع المحتوى بالشكل المناسب:
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