## Tuesday, May 12, 2009

I needed a way to do a file upload from client to server without using FTP and found this easy solution using the FileUpload control.

Duh.

The control appears as a texbox with a Browse... button. The following puts the control on the page and sets the file to be uploaded to directory C:\\rptsys on the server.

Added a button to initiate the upload and a label to display the result:

<asp:Button ID="Button1" runat="server" Text="UploadFile" onclick="Button1_Click" /> </div> <asp:Label ID="Label1" runat="server" Text="Label"Width="247px"></asp:Label>

I put together a simple UI:

The Browse button opens up a full choose file dialog window.

The backend code:
  protected void Button1_Click(object sender, EventArgs e)       {           if (FileUpload1.HasFile)               {                    Label1.Text = "File Uploaded: " + FileUpload1.FileName;                    FileUpload1.SaveAs(@"C:\temp\uploads\" +FileUpload1.FileName);               }               else               {                   Label1.Text = "No File Uploaded.";               }       }

After the file is transmitted, I display a "success" message.

I would have liked to prepopuate the Browse textbox to the directory I know the file is in, but apparently, this cannot be done for security reasons.

#### 1 comment:

1. You can prepopuate the textbox via JavaScript: