我正在尝试使用文件上传控件来上传和下载文件,使用的是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();
}
}
}
Server.MapPath("Files/" + filename)
放入一个变量中。然后,在调试期间,您可以查看它的值。它看起来正确吗?您实际上是否有一个名为“Files”的目录,并且该目录对于Web应用程序具有正确的写入权限? - Andrew Morton~/
:fileUpload1.SaveAs(Server.MapPath("~/
Files/" + filename)); - Avijit