问题
I am making a module that shows the tree view of documents that are stores on my drive in a folder. It is retrieving well. But the problem is that the documents are in different format like(.pdf, .docx etc). That are not opening in browser on click. There it shows a 404.4 error. So Tell me how can I download/open different format files through button click? The following is my code:
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 + "-->");
}
}
}
}
回答1:
404.4 means that the web server (IIS presumably) does not now how to serve the file (based on extension). If your code is serving other files correctly, this is a web server configuration issue. Check your servers documentation for adding the appropriate handlers for the file extensions that aren't working.
回答2:
I would use a hyperlink in your treeview that opens the link: openfile.ashx?path=[insertpathhere] (make sure that your link opens in target="_blank")
within your Generic Handler (ASHX) you have access to load a file from Disk, and stream its bytes into the responseStream. and that will cause the file to download at the browser. You should also set the content-type where applicable.
Code Sample Requested...
Preface: There are some "extra" things going on here... I base64 Encoded the path in my example because I didnt want the path to be 'human-readable'. Also, when I handed it off to the browser I am pre-pending 'export-' plus a timestamp... but you get the idea...
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; } }
}
来源:https://stackoverflow.com/questions/6543673/how-to-download-open-the-file-that-i-retrive-by-server-path