【发布时间】:2020-04-18 16:32:06
【问题描述】:
我想使用asp.net application webforms上传图片等文件。
应用程序.netfaramwork 是4.6.1。
我对网站项目没有任何问题,但网络表单会引发异常错误。
这是我的aspx 页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="uploadfile.aspx.cs" Inherits="fileUploadTest.uploadfile" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>upload image</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Browse to Upload File</p>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_Click" />
</p>
</form>
<p>
<asp:Label runat="server" ID="FileUploadStatus"></asp:Label>
</p>
</body>
</html>
aspx.cs 后面的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace fileUploadTest
{
public partial class uploadfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
{
string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string SaveLocation = Server.MapPath("upload") + "\\" + fn;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
FileUploadStatus.Text = "The file has been uploaded.";
}
catch (Exception ex)
{
FileUploadStatus.Text = "Error: " + ex.Message;
}
}
else
{
FileUploadStatus.Text = "Please select a file to upload.";
}
}
}
}
我已经在application根目录下创建了一个文件夹,命名为upload。
但是当我从系统中选择文件后单击按钮时,会引发如下错误:
错误:找不到文件 'C:\Users\mybla\Documents\Visual Studio 2017\Projects\05.学习\fileUploadTest\fileUploadTest\upload\logo.png'。
logo.png 是我从系统中选择的文件。我什至试试这个代码:
if (Directory.Exists(Server.MapPath("~/upload/"))){
FileUpload1.SaveAs(Server.MapPath("~/upload/" + fileName));
}
Directory.Exists() 返回 true 但 FileUpload1.SaveAs() 返回与我提到的相同的错误。
注意:更新#1
我什至尝试以下代码,但错误相同:
var path = Server.MapPath("~/upload/" + FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(path);
【问题讨论】:
标签: c# asp.net file-upload webforms