|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
Back in the ASP world, uploading files via a web page was a tricky problem. The problem was that due to the encryption type of the form used to submit the file from the client's browser, receiving such files on the server side was a complex task. Data had to be retrieved as a safe byte array and decrypted before it could be used. Most of the people resorted to 3rd party DLLs. A few wrote their own DLLs and some even wrote purely ASP solutions to this problem using VBScript. Fortunately for us, the .NET Framework SDK comes with a few classes that make uploading of the files simple from the web developer point of view. This article will demonstrate following concepts:
Setting Up an HTML Form for File UploadingThe requirements for an HTML form to be able to upload files are very simple: you have to use <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
HTML input control that is used to upload file has a simple type of <input id="filMyFile" type="file" runat="server">
This is all that needs to be done to an HTML form for a client to be able to submit a file to your ASP.NET application. Receiving Uploaded Files
protected HtmlInputFile filMyFile;
if( filMyFile.PostedFile != null )
{
// File was sent
}
else
{
// No file
}
The
Let's find out the size of the file: // Get a reference to PostedFile object
HttpPostedFile myFile = filMyFile.PostedFile;
// Get size of uploaded file
int nFileLen = myFile.ContentLength;
Now that we know the size, we can move on to retrieving the data. First, we need to allocate a byte array to store the data: // Allocate a buffer for reading of the file
byte[] myData = new byte[nFileLen];
Next, we can read the uploaded file in our buffer using the // Read uploaded file from the Stream
myFile.InputStream.Read(myData, 0, nFileLen);
At this point, we have successfully retrieved the uploaded file into a byte array called Saving Uploaded Files to DiskI wrote a simple function for my demo project that stores files to a disk: // Writes file to current folder
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
FileStream newFile = new FileStream(strPath, FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}
I pass a full path of where I want a file to be stored and reference to a buffer with file data to this function. It uses the string strFilename = Path.GetFileName(myFile.FileName);
Security is another matter. In my demo project, I store files in the same folder where the project is executed. In order for that to work, the ASPNET account (the account that is used to execute ASP.NET processes) has to have Write permissions on that folder. By default it does not, so you need to right-click the folder, go to the security tab and add the ASP.NET account to the list. Then grant write permissions to that account by checking the Write checkbox and click OK. Saving Uploaded Files to a DatabaseThe following function is used in my demo project to store uploaded files in the database: // Writes file to the database
private int WriteToDB(string strName, string strType, ref byte[] Buffer)
{
int nFileID = 0;
// Create connection
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());
// Create Adapter
OleDbDataAdapter dbAdapt = new OleDbDataAdapter("SELECT * FROM tblFile", dbConn);
// We need this to get an ID back from the database
dbAdapt.MissingSchemaAction = MissingSchemaAction.AddWithKey;
// Create and initialize CommandBuilder
OleDbCommandBuilder dbCB = new OleDbCommandBuilder(dbAdapt);
// Open Connection
dbConn.Open();
// New DataSet
DataSet dbSet = new DataSet();
// Populate DataSet with data
dbAdapt.Fill(dbSet, "tblFile");
// Get reference to our table
DataTable dbTable = dbSet.Tables["tblFile"];
// Create new row
DataRow dbRow = dbTable.NewRow();
// Store data in the row
dbRow["FileName"] = strName;
dbRow["FileSize"] = Buffer.Length;
dbRow["ContentType"] = strType;
dbRow["FileData"] = Buffer;
// Add row back to table
dbTable.Rows.Add(dbRow);
// Update data source
dbAdapt.Update(dbSet, "tblFile");
// Get newFileID
if( !dbRow.IsNull("FileID") )
nFileID = (int)dbRow["FileID"];
// Close connection
dbConn.Close();
// Return FileID
return nFileID;
}
The Access database that I used in the demo project has only one table FileID – autonumber Filename – text 255 FileSize - long integer ContentType – text 100 FileData – OLE Object The code in the above function is very straightforward. I create The local ASP.NET account has to have Write permissions to a database file in order for your code to succeed. If your file is placed anywhere under Retrieving of a File from a DatabaseI used the same ASPX page to read and return file data out of the database in my demo project. I check for the FileID parameter being passed to a page. If it was passed, I know that I need to return a file rather than process the user's input: private void Page_Load(object sender, System.EventArgs e)
{
// Check if FileID was passed to this page as a parameter
if( Request.QueryString["FileID"] != null )
{
// Get the file out of database and return it to requesting client
ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
}
}
The // Read file out of the database and returns it to client
private void ShowTheFile(int FileID)
{
// Define SQL select statement
string SQL = "SELECT FileSize, FileData, ContentType FROM tblFile WHERE FileID = "
+ FileID.ToString();
// Create Connection object
OleDbConnection dbConn = new OleDbConnection(GetConnectionString());
// Create Command Object
OleDbCommand dbComm = new OleDbCommand(SQL, dbConn);
// Open Connection
dbConn.Open();
// Execute command and receive DataReader
OleDbDataReader dbRead = dbComm.ExecuteReader();
// Read row
dbRead.Read();
// Clear Response buffer
Response.Clear();
// Set ContentType to the ContentType of our file
Response.ContentType = (string)dbRead["ContentType"];
// Write data out of database into Output Stream
Response.OutputStream.Write((byte[])dbRead["FileData"], 0, (int)dbRead["FileSize"]);
// Close database connection
dbConn.Close();
// End the page
Response.End();
}
I am using Security ConsiderationsImportant: Because my demo project writes files to disk or data to an Access database, you need to make sure that security permissions are set properly on folders and files where you want to write. Beta versions of .NET used the In order to make my demo project work under the .NET release version, you need to place it in a folder (anywhere under
|
||||||||||||||||||||||