ASP.Net FileUpload

File Upload was one of those things that confuse programmers new to the web development atmosphere.

You develop a program on your local computer, maybe it has an import function. So you provide a file called c:\test.txt. You deliver your program to production, and you have odd problems.

The problem is c:\test.txt now refer’s to a file on the C drive of the web server. In all likelyhood the web server places your code in a sandbox, and wouldn’t even be able to reach that file if it were there.

The FileUpload object is pretty cool, it is similar to the <Input type=’File’ … except it trivializes it to something a lot simpler than how files were handled in ASP.

As with ASP, you want to upload a file like c:\test.bat - but when you are running a web server application c:\test.bat is pointing to the c drive on the file server. Consequently things get a bit tricky. For any processing to occur the file upload control must copy the file to a space the webserver can access. Typically I setup an upload folder and then add it’s location to my app.config file.

Here is a sample of the html

1
2
3
<asp:FileUpload 
ID="FileUploadFilename"
runat="server" />

Here is a sample of the code

1
2
3
4
5
6
7
8
9
10
11
Dim FileName As String _
= SI.sys.appSetting("UploadDirectory") & FileUploadFilename.FileName

Try
FileUploadFilename.SaveAs(filename)
Catch ex As Exception

Literal1.Text = "Error trying to copy the file to the server (with the name " & FileName & ": " & ex.Message

Exit Sub
End Try

Assuming this command works, what will happen is a file will be placed onto the upload directory.