【发布时间】:2016-01-08 04:36:13
【问题描述】:
我正在尝试使用文件上传控件上传然后使用 Asp.net C# 下载文件,但它给了我一个未找到目录的异常。任何人都可以帮我解决这个问题,我在哪里犯了错误?
这是我的 .aspx 文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="fileuploadcheck.aspx.cs" Inherits="fileuploadcheck" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="padding: 20px;">
<tr>
<td>
<asp:Label ID="lblFilename" runat="server" Text="Browse:"></asp:Label>
</td>
<td>
<asp:FileUpload ID="fileUpload1" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="OnLnkUpload" runat="server" OnClick="OnLnkUpload_Click" Font-Underline="False">Upload</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="OnLnkDownload" runat="server" OnClick="OnLnkDownload_Click" Font-Underline="False">Download</asp:LinkButton>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
这是我的代码隐藏文件:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public partial class fileuploadcheck : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// To save/upload files in folder and download files from folder in asp.net
/// </summary>
string filename = string.Empty;
protected void btnUpload_Click(object sender, EventArgs e)
{
}
protected void OnLnkUpload_Click(object sender, EventArgs e)
{
filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
Response.Write("File uploaded sucessfully.");
lblFilename.Text = "Files/" + fileUpload1.FileName;
}
// To download uplaoded file
protected void OnLnkDownload_Click(object sender, EventArgs e)
{
if (lblFilename.Text != string.Empty)
{
if (lblFilename.Text.EndsWith(".txt"))
{
Response.ContentType = "application/txt";
}
else if (lblFilename.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
else if (lblFilename.Text.EndsWith(".docx"))
{
Response.ContentType = "application/docx";
}
else
{
Response.ContentType = "image/jpg";
}
string filePath = lblFilename.Text;
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
}
}
【问题讨论】:
-
你能告诉我们它究竟在哪里引发了异常吗?
-
如果异常出现在保存部分,我认为您可能需要在 Mappath 中的文件之前添加一个“~”
-
protected void OnLnkUpload_Click(object sender, EventArgs e) { filename = Path.GetFileName(fileUpload1.PostedFile.FileName); fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
-
执行这行代码时出现异常
-
将您的
Server.MapPath("Files/" + filename)放入一个变量中。然后,当你调试它时,你可以看到它的值。看起来对吗?您实际上是否有一个名为“Files”的目录,该目录对您的 Web 应用程序具有正确的写入权限?