文件内容查看器在浏览器上使用asp.net
本文关键字:asp net 浏览器 文件 | 更新日期: 2023-09-27 18:16:24
如何在asp.net浏览器上查看上传文件的内容 ?是否有可能使用通用代码查看所有类型文件的内容?或者那里有免费的项目吗?
谢谢. .
您将无法看到任何文件的内容,因为这将要求有关浏览器具有显示特定文件的插件。以MS项目文件、Corel绘图文件、Auto CAD等为例。浏览器不会显示这些文件,因为AFAIK,没有为这些文件提供插件,可以被浏览器用来嵌入一个查看器。
一般来说,浏览器会很高兴地显示pdf(如果安装了Acrobat Reader)、图像、TXT文件和其他一些文件。
因此,您可以执行以下操作来读取所有文件:
DirectoryInfo info = new DirectoryInfo("PhysicalPathToFiles");
GridView1.DataSource=info.GetFiles();
GridView1.DataBind();
并设置GrdiView1标记,仅绑定FileName属性和所需的其他所有内容。您可能希望在该列上构造一个超链接,以便在单击文件名时,根据文件类型要求用户下载/查看该文件。
假设您将所有文件绑定到Gridview,就像我上面解释的那样。有了这样一个GridViewColumn,应该允许用户点击任何文件并在浏览器中看到它。
<asp:HyperLinkColumn
HeaderText="File Name"
DataNavigateUrlField="Name"
DataNavigateUrlFormatString="UploadedFiles/{0}"
DataTextField="Name"
/>
其中UploadedFiles
是应用程序中保存这些文件的虚拟目录
为了允许用户查看内联文件,您需要将文件流式传输给用户并在header中设置一些值。
我们通常使用映射到"虚拟"页面(即Download.aspx)的HTTP处理程序来执行此操作,以便可以在弹出窗口中从客户端调用它,而不会影响调用页面。
此机制可用于下载或查看内联文件。
下面是在类的StreamFileToUser方法中实现的下载过程的描述:
如果调用者请求下载,则检查mime类型集合以确定文件是否包含受支持的mime类型,这意味着它有机会内联显示给用户。
如果找到mime类型,我们使用内联指令要求浏览器将文件显示给用户。如果浏览器不支持此mime类型的内联,则会提示用户下载。
如果没有找到mime类型,则直接发出下载命令。
打开IIS管理器,选择web服务器图标,双击mime类型图标,可以获得IIS内mime类型的完整列表(假设为7+)。
下面是一个HTTP处理程序类的例子:public class DownloadRequestHandler : System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// This method is used to process the incoming request
/// </summary>
/// <param name="oContext"></param>
/// <remarks></remarks>
public void ProcessRequest(HttpContext oContext)
{
try
{
string sFileName = null;
string sSourceFilePath = null;
// Should add existence checking here
sFileName = oContext.Request.QueryString["FileName"];
// Assume that the files are stored in the relative directory Files. Should add existence checking here
sSourceFilePath = System.IO.Path.Combine(oContext.Server.MapPath("Files"), sFileName);
StreamFileToUser(GenerateStandardMimeList(), sSourceFilePath, sFileName, oContext.Response, false, false);
}
catch (System.Threading.ThreadAbortException theException)
{
// Do nothing
}
catch (Exception theException)
{
SendErrorToUser(oContext.Response, theException.Message);
}
}
/// <summary>
/// This method streams a file to a user
/// </summary>
/// <param name="cMimeTypes">The set of known mimetypes. This is only needed when the file is not being downloaded.</param>
/// <param name="sFileName"></param>
/// <param name="sFileNameForUser"></param>
/// <param name="theResponse"></param>
/// <param name="fDownload"></param>
/// <returns></returns>
/// <remarks></remarks>
public bool StreamFileToUser(System.Collections.Generic.Dictionary<string, string> cMimeTypes, string sFileName, string sFileNameForUser, HttpResponse theResponse, bool fDownload = true, bool fOkToDeleteFile = false)
{
// Exceptions are handled by the caller
bool fDontEndResponse = false;
sFileNameForUser = CleanFileName(sFileNameForUser);
// Ensure there is nothing else in the response
try
{
try
{
// Remove what other controls may have been put on the page
theResponse.ClearContent();
// Clear any headers
theResponse.ClearHeaders();
}
catch (System.Web.HttpException theException)
{
// Ignore this exception, which could occur if there were no HTTP headers in the response
}
bool fFoundIt = false;
if (!fDownload)
{
string sExtension = null;
sExtension = System.IO.Path.GetExtension(sFileNameForUser);
if (!(string.IsNullOrEmpty(sExtension)))
{
sExtension = sExtension.Replace(".", "");
if (cMimeTypes.ContainsKey(sExtension))
{
theResponse.ContentType = cMimeTypes[sExtension];
theResponse.AddHeader("Content-Disposition", "inline; filename=" + sFileNameForUser);
fFoundIt = true;
}
}
}
if (!fFoundIt)
{
theResponse.ContentType = "application/octet-stream";
theResponse.AddHeader("Content-Disposition", "attachment; filename=" + sFileNameForUser);
}
theResponse.TransmitFile(sFileName);
// Ensure the file is properly flushed to the user
theResponse.Flush();
}
finally
{
// If the caller wants, delete the file before the response is terminated
if (fOkToDeleteFile)
{
System.IO.File.Delete(sFileName);
}
}
// Ensure the response is closed
theResponse.Close();
if (!fDontEndResponse)
{
try
{
theResponse.End();
}
catch
{
}
}
return true;
}
/// <summary>
/// This method generates a standard list of extension to content-disposition tags
/// The key for each item is the file extension without the leading period. The value
/// is the content-disposition.
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public System.Collections.Generic.Dictionary<string, string> GenerateStandardMimeList()
{
// Exceptions are handled by the caller.
System.Collections.Generic.Dictionary<string, string> cItems = new Dictionary<string, string>();
cItems.Add("jpeg", "image/jpeg");
cItems.Add("jpg", "image/jpeg");
cItems.Add("pdf", "application/pdf");
cItems.Add("csv", "application/vnd.ms-excel");
cItems.Add("doc", "application/msword");
cItems.Add("docx", "application/vnd.ms-word.document.12");
cItems.Add("xls", "application/vnd.ms-excel");
cItems.Add("xlsx", "application/vnd.ms-excel.12");
return cItems;
}
/// <summary>
/// This method removes all invalid characters from the specified file name.
/// Note that ONLY the file name should be passed, not the directory name.
/// </summary>
/// <param name="sFileName"></param>
/// <returns></returns>
/// <remarks></remarks>
public string CleanFileName(string sFileName)
{
// Exceptions are handled by the caller
// If there are any invalid characters in the file name
if (sFileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
{
// Strip them out (split to remove the characters, then rejoin the pieces into one string)
return string.Join("", sFileName.Split(System.IO.Path.GetInvalidFileNameChars()));
}
else
{
return sFileName;
}
}
public void SendErrorToUser(HttpResponse theResponse, string sError)
{
// Note that errors are handled by the caller
sError = "<script>alert('"" + sError.Replace("'"", "").Replace(Environment.NewLine, "''n") + "'");</script>";
// Ensure there is nothing else in the response
theResponse.Clear();
theResponse.Write(sError);
theResponse.Flush();
}
}
在你的网页。配置,将以下行添加到httphandlers
部分,并根据需要替换名称空间:
<add path="download.aspx" verb="*" type="MyWebApp.DownloadRequestHandler, MyWebApp" validate="false" />
那么你的下载请求是:
download.aspx?FileName=thefile.pdf
和上面的代码假设文件存储在网站的files子目录中