An ASP.NET 2.0 Script To Share Files Among Users

Recently asked on Yahoo! Answers:

How could I enable user to upload and download file from server using asp.net 2?

How could I enable a user to upload file to the server and then view link to download this file from the server to anthor user i when he enters the site using ASP.NET 2?

The problems here could be handled very easily simply by using the built-in FileUpload class and the DirectoryInfo / FileInfo classes to display the files in the targeted directory.

So, let’s run that simple code today.

Web.config Settings

We’ll set a few application variables in the web.config file to make our application very portable. We need to record:

  • The URI (that is, the physical path) to the file
  • The URL (that is, the hyperlink) to the file
  • We’ll also add the System.IO namespace to the namespaces

	
	


	

The HTML Form

With the keys and namespaces added, we can move on to the HTML.

  • We need the FileUpload control, as well as a RequiredFieldValidator to make sure that if someone uploads a file, they’ve entered something in the control.
  • We need a button to submit the form.
  • Finally, we have a DIV that we will programmatically update with the available file list.

	

	
	

Uploaded Files

Upload Your File

File To Upload:

With the HTML out of the way, we need three subroutines:

  • A Page_Load subroutine that will show all users the file list upon first visiting the page.
  • A subroutine to show us the files
  • A subroutine to upload user files, then refresh the file list

The Page_Load Subroutine

It doesn’t get more rudimentary than this: Check for page postback; if the page isn’t posting back, show the list of files.

Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
	If Not Page.IsPostBack Then
		'as the name says, show files
		ShowAvailableFiles()
	End If
End Sub

The ShowAvailableFiles Subroutine

Showing the files is fairly straightforward.

  • We create an HTML table
  • We open the directory up with DirectoryInfo, then get all the files from it
  • We load those files into an array of FileInfo objects
  • We check the length of the array. If it’s 0, we know there are no files. If it’s longer, we know there are files to display.
  • We iterate through the FileInfo array we created, constructing URLs for each file and showing its upload (LastWriteTime) time.
  • We finish the HTML table, and then assign the table to the display DIV’s InnerHtml
Sub ShowAvailableFiles()
	'display all available files in a table
	Dim strOut As String, strPath As String, strBase As String = ConfigurationManager.AppSettings("UploadBaseURL").ToString()

	'start building the table
	strOut = "
"
	strOut += "


"

	'get all the files in our upload directory
	'load into an array of FileInfo objects
	Dim objDir As New DirectoryInfo(ConfigurationManager.AppSettings("UploadBaseURI").ToString())
	Dim objFiles() As FileInfo = objDir.GetFiles()
	Dim objFile As FileInfo

	'if we have no files, put message out
	If objFiles.Length = 0 Then
		strOut += "


"
	Else
		For Each objFile In objFiles
			'provide a link to each file, as well as its upload date / time
			'(LastWriteTime is the proper use here; CreateTime may be the
			'date the file was made, not the date it was uploaded
			strPath = strBase + objFile.Name
			strOut += "


"
			strOut += "


"
		Next
	End If

	'close the table, set the HTML for the DIV to show the listing
	strOut += "
File Date / Time Uploaded
No files
" + objFile.Name + "" + String.Format("{0:F}", objFile.LastWriteTime) + "
" divFiles.InnerHtml = strOut End Sub

The btnSubmit_onClick Subroutine

The last task is the subroutine that handles file uploading.

  • It checks if there was a file sent via the FileUpload control
  • If so, it tries to save the uploaded file to the URI for our uploaded files
  • If the file upload was bad, an error message is output
  • The available file list is refreshed
Sub btnSubmit_onClick(ByVal Sender As Object, ByVal E As EventArgs)
	'check for good file
	If fuMain.HasFile() Then
		'set upload path string from app key
		Dim strPath As String = ConfigurationManager.AppSettings("UploadBaseURI").ToString() + fuMain.FileName
		'if we have a good upload, tell user;
		'otherwise, tell user the problem
		Try
			fuMain.SaveAs(strPath)
		Catch ex As Exception
			lblStatus.Text = "Error trying to save the file you uploaded: " + ex.Message
		Finally
			'no matter what, refresh the file list
			ShowAvailableFiles()
		End Try
	Else
		'warn that no file was sent to server
		lblStatus.Text = "No file was uploaded. Please try again."
	End If
End Sub

Final Notes

You can download this code here:

ASP.NET 2.0 Simple Upload Code

I distribute code under the latest version of the Creative Commons Attribution / Share-Alike License.

There are all kinds of security holes in this code. Ideally, you should never place a writable directory in your public HTML path, nor should you allow people to upload any old thing they want. If you use this as is, someone could upload a malicious page to your Web site and do all sorts of damage with it; they could distribute illegal materials via your site; the list of potential mischief is endless.

As the license states, this code is provided as-is with no warranty whatsoever.

Comments Closed

Comments are closed for this post. If you have questions, would like assistance, or otherwise would like to discuss this post, please contact me directly.