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

时间:2013-03-10 09:24:30

标签: c# asp.net file-upload

我正在尝试使用ASP.NET进行简单的上传文件控制, 它不会起作用:

这是我的代码(.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;
    }
  }

该文件未显示在服务器中.. 有什么想法吗?

当我断点时,它们都变为有效,应用程序到达代码,它全部工作,但不会将其保存到文件夹中。

1 个答案:

答案 0 :(得分:1)

变化

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

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