如何启用用户从您的 ASP.NET 站点下载 Office 文档





0/5 (0投票)
客户或网站用户的一个常见需求是启用文档的上传和下载。这些文档可以是电子表格、演示文稿
客户或网站用户的一个常见需求是启用文档的上传和下载。这些文档可以是电子表格、演示文稿和 Word 文档。根据服务器的配置,这可能很容易,也可能很难,具体取决于您的网站托管服务器支持哪些 MIME 类型。
默认情况下,许多 Web 服务器配置为对未知内容类型报告 text/plain 或 application/octet-stream MIME 类型。随着新的内容类型被发明或添加到 Web 服务器,Web 管理员可能未能将新的 MIME 类型添加到其 Web 服务器的配置中,从而实际上使您的解决方案的用户无法从您的网站下载任何未知 MIME 类型的的文件。
幸运的是,这可以通过在您的解决方案中添加一个下载页面来轻松解决
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>
Codebehind:
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;
}
}
This solution supports the most commom mime-types and can be easily extended to support other formats.
You can find many of the existing mimetypes here:
http://www.iana.org/assignments/media-types/application/index.html
Happy coding
Tonny