fileupload control wouldn't work in ASP.NET

2019-08-14 18:00发布

I'm trying to make a simple uploadfile control with ASP.NET, and it wouldnt work:

Here's my code(.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>

and here's my code behind(.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;
    }
  }

the file is not presented in the server.. any thoughts?

when I breakpoint, they all goes valid, the application gets to the code, it all working , but won't save it to the folders.

3条回答
家丑人穷心不美
2楼-- · 2019-08-14 18:44

This may or may not work entirely, but you need to include an enctype attribute in your form.

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

If you don't do that, browsers won't transfer the file.

See here: https://developer.mozilla.org/en-US/docs/HTML/Element/form#attr-enctype

查看更多
对你真心纯属浪费
3楼-- · 2019-08-14 18:51

change

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

with

fileupload1.PostedFile.SaveAs(Server.MapPath("~/img/") + filename);
查看更多
唯我独甜
4楼-- · 2019-08-14 18:59

I think the problem lies in these two lines

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

why are you using

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

It should be simple

fileupload1.SaveAs(Server.MapPath("~/img/") + fileupload1.FileName);
查看更多
登录 后发表回答