文件下载解决方案

在现代互联网应用中,用户经常需要从网站下载各种类型的文件,如电子表格、演示文稿和文档。然而,服务器的配置可能会限制某些文件类型的下载。默认情况下,许多Web服务器配置为对未知内容类型报告text/plain或application/octet-stream MIME类型。随着新的内容类型不断被发明或添加到Web服务器,网站管理员可能会忘记将新的MIME类型添加到其Web服务器的配置中,这实际上使得解决方案的用户无法从网站下载任何未知MIME类型的文件。

幸运的是,这个问题可以通过添加一个下载器页面到解决方案中轻松解决。下面是一个简单的下载器页面的示例,它使用ASP.NET技术构建。

以下是一个名为Downloader.aspx的简单下载器页面的代码示例。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownLoader.aspx.cs" Inherits="usability_DownLoader" EnableEventValidation="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> Downloader </div> </form> </body> </html> using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class usability_DownLoader : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["file"] != null) { string fileId = Request.QueryString["file"].ToString(); DownloadFile(fileId); } } protected void DownloadFile(string fileId) { string filePath = QueryFileNameInDB(fileId); string fileName = Path.GetFileName(filePath); Response.Clear(); Response.ContentType = GetMimeType(fileName); string encodefileName = HttpUtility.UrlEncode(fileName); Response.AppendHeader("Content-Disposition", "attachment;filename=" + encodefileName); Response.WriteFile(fileName); Response.End(); Response.Flush(); } protected string GetMimeType(string fileName) { string mimeType = ""; string docType = fileName.LastIndexOf("."); int startDocType = docType.LastIndexOf("."); docType = docType.Substring(startDocType + 1); switch (docType) { case "doc": { mimeType = "application/msword"; break; } case "xls": { mimeType = "application/vnd.ms-excel"; break; } case "xlsx": { mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; } case "ppt": { mimeType = "application/vnd.ms-powerpoint"; break; } case "pptx": { mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; break; } case "docx": { mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break; } default: { mimeType = "application/pdf"; break; } } return mimeType; } }
沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485