如何下载/打开我通过服务器路径检索的文件
本文关键字:服务器 路径 检索 文件 何下载 下载 | 更新日期: 2023-09-27 18:00:55
我正在制作一个模块,显示存储在驱动器文件夹中的文档的树状视图。它恢复得很好。但问题是,这些文档的格式不同,比如(.pdf、.docx等(。单击时不会在浏览器中打开。显示404.4错误。告诉我如何通过点击按钮下载/打开不同格式的文件?以下是我的代码:
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
if (Settings["DirectoryPath"] != null)
{
BindDirectory(Settings["DirectoryPath"].ToString());
}
else
{
BindDirectory(Server.MapPath("~/"));
}
}
}
catch (DirectoryNotFoundException DNEx)
{
try
{
System.IO.Directory.CreateDirectory("XIBDir");
BindDirectory(Server.MapPath("XIBDir"));
}
catch (AccessViolationException AVEx)
{
Response.Write("<!--" + AVEx.Message + "-->");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
#region Optional Interfaces
/// -----------------------------------------------------------------------------
/// <summary>
/// Registers the module actions required for interfacing with the portal framework
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
return Actions;
}
}
#endregion
private void BindDirectory(string Path)
{
try
{
System.IO.DirectoryInfo dirRoot = new System.IO.DirectoryInfo(Path);
TreeNode tnRoot = new TreeNode(Path);
tvDirectory.Nodes.Add(tnRoot);
BindSubDirectory(dirRoot, tnRoot);
tvDirectory.CollapseAll();
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnRoot = new TreeNode("Access Denied");
tvDirectory.Nodes.Add(tnRoot);
}
}
private void BindSubDirectory(System.IO.DirectoryInfo dirParent, TreeNode tnParent)
{
try
{
foreach (System.IO.DirectoryInfo dirChild in dirParent.GetDirectories())
{
//TreeNode tnChild = new TreeNode(dirChild.Name);
TreeNode tnChild = new TreeNode(dirChild.Name, dirChild.FullName);
tnParent.ChildNodes.Add(tnChild);
BindSubDirectory(dirChild, tnChild);
}
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnChild = new TreeNode("Access Denied");
tnParent.ChildNodes.Add(tnChild);
}
}
private void BindFiles(string Path)
{
try
{
tvFile.Nodes.Clear();
System.IO.DirectoryInfo dirFile = new System.IO.DirectoryInfo(Path);
foreach (System.IO.FileInfo fiFile in dirFile.GetFiles("*.*"))
{
string strFilePath = Server.MapPath(fiFile.Name);
string strFilePaths = "~/" + fiFile.FullName.Substring(15);
TreeNode tnFile = new TreeNode(fiFile.Name, fiFile.FullName, "", strFilePaths, "_blank");
tvFile.Nodes.Add(tnFile);
}
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
protected void tvDirectory_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
string strFilePath = tvDirectory.SelectedNode.Value;
BindFiles(tvDirectory.SelectedNode.Value);
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
}
}
404.4意味着web服务器(可能是IIS(现在不知道如何为文件提供服务(基于扩展名(。如果您的代码正确地为其他文件提供服务,则这是web服务器配置问题。查看服务器文档,为不起作用的文件扩展名添加适当的处理程序。
我会在树视图中使用一个超链接来打开链接:openfile.ashx?path=[insertpathhere](确保您的链接在target="_blank"中打开(
在通用处理程序(ASHX(中,您有权从磁盘加载文件,并将其字节流式传输到responseStream中。并且这将导致该文件在浏览器处下载。您还应该在适用的情况下设置内容类型。
请求的代码示例。。。
前言:这里有一些"额外"的事情在发生。。。我对示例中的路径进行了base64编码,因为我不希望路径是"可读的"。此外,当我把它交给浏览器时,我正在预先挂起"导出-"加上时间戳。。。但你明白了。。。
public class getfile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var targetId = context.Request.QueryString["target"];
if (string.IsNullOrWhiteSpace(targetId))
{
context.Response.ContentType = "text/plain";
context.Response.Write("Fail: Target was expected in querystring.");
return;
}
try
{
var url = new String(Encoding.UTF8.GetChars(Convert.FromBase64String(targetId)));
var filename = url.Substring(url.LastIndexOf('''') + 1);
filename = "export-" + DateTime.Now.ToString("yyyy-MM-dd-HHmm") + filename.Substring(filename.Length - 4);
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", filename));
var data = File.ReadAllBytes(url);
File.Delete(url);
context.Response.BinaryWrite(data);
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write("Error occurred: " + ex.Message);
context.Response.ContentType = "text/plain";
context.Response.End();
}
}
public bool IsReusable { get { return false; } }
}