1

我正在尝试使用 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;
    }
  }

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

当我断点时,它们都有效,应用程序获取代码,一切正常,但不会将其保存到文件夹中。

4

3 回答 3

2

这可能会也可能不会完全起作用,但您需要enctype在表单中包含一个属性。

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

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

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

于 2013-03-10T09:38:06.647 回答
1

改变

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

fileupload1.PostedFile.SaveAs(Server.MapPath("~/img/") + filename);
于 2013-03-10T09:38:53.243 回答
0

我认为问题在于这两行

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);
于 2013-03-10T09:46:51.990 回答