【问题标题】:How to download/open the file that I retrive by server path?如何下载/打开我通过服务器路径检索的文件?
【发布时间】:2011-07-01 04:44:59
【问题描述】:

我正在制作一个模块,该模块显示存储在我的驱动器上的文件夹中的文档的树视图。它恢复得很好。但问题是文档格式不同,例如(.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 + "-->");
        }
    }
}

}

【问题讨论】:

    标签: c# asp.net dotnetnuke


    【解决方案1】:

    404.4 表示 Web 服务器(大概是 IIS)现在不如何提供文件(基于扩展名)。如果您的代码正确地为其他文件提供服务,则这是一个 Web 服务器配置问题。检查您的服务器文档,为不起作用的文件扩展名添加适当的处理程序。

    【讨论】:

      【解决方案2】:

      我会在您的树视图中使用打开链接的超链接:openfile.ashx?path=[insertpathhere](确保您的链接在 target="_blank" 中打开)

      在您的通用处理程序 (ASHX) 中,您可以访问从磁盘加载文件,并将其字节流式传输到 responseStream。这将导致文件在浏览器中下载。您还应该在适用的情况下设置内容类型。

      请求代码示例...

      前言:这里发生了一些“额外”的事情......我在我的示例中对路径进行了 base64 编码,因为我不希望路径是“人类可读的”。另外,当我将它交给浏览器时,我会预先设置“export-”加上一个时间戳……但你明白了……

      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; } }
      }
      

      【讨论】:

      • 为您的项目添加正确的类型...添加>新项目...>通用处理程序
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多