fileupload控件在ASP.NET中不起作用

本文关键字:不起作用 NET ASP 控件 fileupload | 更新日期: 2023-09-27 18:03:15

我试图使一个简单的上传文件控制与ASP。网这是行不通的:

下面是我的代码(.aspx):
<form id="form1" runat="server">
  <div>
    upload a file now.
      <asp:FileUpload ID="fileupload1" runat="server" />
      <asp:Button  ID="button1"  Text="Upload"  runat="server"  Width="73px" 
            onclick="button1_Click" />
    <asp:Label ID="Label1" runat="server"  Font-Bold="True"  ForeColor="#000099">
         </asp:Label>
  </div>  
</form>
这是我的代码后面(.cs):
if(fileupload1.HasFile)
{
    try
    {
        if(fileupload1.PostedFile.ContentType ==  "image/jpeg")
        {
            if(fileupload1.PostedFile.ContentLength < 51200000)
            {
               string  filename = Path.GetFileName(fileupload1.FileName);
               fileupload1.SaveAs(Server.MapPath("~/img/") + filename);
               Label1.Text ="File uploaded successfully!";
            }
            else
                Label1.Text ="File maximum size is 500 Kb";
        }
        else
            Label1.Text ="Only JPEG files are accepted!";
    }
    catch(Exception exc)
    {
        Label1.Text = "The file could not be uploaded. The following error occured: "
                           + exc.Message;
    }
  }

文件没有在服务器中呈现。任何想法吗?

当我断点时,它们都是有效的,应用程序得到代码,它都工作,但不会将其保存到文件夹

fileupload控件在ASP.NET中不起作用

这可能完全有效,也可能不完全有效,但是您需要在表单中包含一个enctype属性。

<form id="form1" runat="server" enctype="multipart/form-data">

如果你不这样做,浏览器将不会传输文件。

请看这里:https://developer.mozilla.org/en-US/docs/HTML/Element/form#attr-enctype

change

fileupload1.SaveAs(Server.MapPath("~/img/") + filename);

fileupload1.PostedFile.SaveAs(Server.MapPath("~/img/") + filename);

我认为问题出在这两行

string  filename = Path.GetFileName(fileupload1.FileName);
fileupload1.SaveAs(Server.MapPath("~/img/") + filename);

为什么要用

 string  filename = Path.GetFileName(fileupload1.FileName);

应该很简单

fileupload1.SaveAs(Server.MapPath("~/img/") + fileupload1.FileName);