一次上传多个文件
本文Haissam Abdul Malak介绍了如何一次上传多个文件
Introduction | |
[ Back To Top ]
I'm sure that you have seen a lot of examples about how to upload multiple files using multiple instances of the HtmlInputFile (ASP.NET 1.1) or the FileUpload control (ASP.NET 2.0). What I tried to do in this article is to provide a way to upload multiple files using one instance of the specified control. Each time the user chooses a file, it will get added to a List Box control where he can also delete a certain file after it has been selected. For each selected file (once being added to the List Box control), I'm saving its information in a session variable and once uploaded has succeeded, the session variables are disposed. Taking into considerations that saving a lot of objects into session variables will increase the load on the server, I restrict the maximum number of uploaded files to 3, and do some checking on the file content to ensure it does not exceed 5 MB. These numbers can all be modified to fit your needs when you implement this. |
|
Starting to Code | |
[ Back To Top ]
The controls being used are 1. One HtmlInputFile control 2. A button to add the file to the list box 3. A list box control to show the user his selected files 4. A delete button to remove a previously selected file 5. A button to save the files into the specific directory The below listing will show how the HTML code will look after we have added the controls into our WebForm. Listing 1 <INPUT style="Z-INDEX: 101; LEFT: 83px;
WIDTH: 489px; POSITION: absolute; TOP: 67px; HEIGHT: 22px" type="file"
runat="server" id="FileUpload" size="62">
<asp:Button id="Button1"
style="Z-INDEX: 102; LEFT: 591px; POSITION: absolute; TOP: 66px"
runat="server" Text="Attach"></asp:Button>
<asp:ListBox id="ListBox1"
style="Z-INDEX: 103; LEFT: 84px; POSITION: absolute; TOP: 104px"
runat="server" Height="93px" Width="565px"></asp:ListBox>
<asp:Button id="Button2"
style="Z-INDEX: 104; LEFT: 339px; POSITION: absolute; TOP: 205px"
runat="server" Text="Upload"></asp:Button>
<asp:Button id="Button3"
style="Z-INDEX: 105; LEFT: 684px; POSITION: absolute; TOP: 131px"
runat="server" Text="Delete" Width="70px"></asp:Button>
Figure 1
Code behind (C#) In this section, we will see how each button click event is handled to provide the correct behavior. Listing 2 private void btnAttach_Click(object sender, System.EventArgs e)
{
// Save the attached file to fileName variable
string fileName = FileUpload.PostedFile.FileName;
// If the counter is null then create one with default value equal to 0
if (ViewState["i"] == null)
{
ViewState["i"] = 0;
}
// Check if a file is selected
if (fileName != null || fileName != string.Empty)
{
// Add it to the collection
ListBox1.Items.Add(FileUpload.PostedFile.FileName);
// Save an index for each selected file
int i = Convert.ToInt32(ViewState["i"]);
// Save the fileupload control into a different session
Session["myupload" + i] = FileUpload;
// Increment the counter
i++;
// Set the ViewSate to the latest counter value.
ViewState["i"] = i;
}
}
In the above listing, we are handling the Attach button click event. First, we will get the selected file name. We used the ViewState to save the counter (how many files selected). If a file has been selected, we will save its filename as a new Item in the ListBox control, then save its instance in the session state. In the final two lines of code, we are updating the counter value and resaving it in ViewState. Figure 2
The figure above is showing the process that we just explained. Each selected item is being added to the ListBox control. Listing 3 private void btnDelete_Click(object sender, System.EventArgs e)
{
if (ListBox1.SelectedIndex > - 1)
{
int uploadedFileIndex = ListBox1.SelectedIndex;
Session.Remove("myupload" + uploadedFileIndex);
ListBox1.Items.Remove(ListBox1.SelectedValue);
}
}
In the above listing, we are handling the delete button click event. First we are checking if an item in the ListBox control is being selected. We are saving the selected index into a variable, setting its specific information in the session state to null, and finally it gets removed from the ListBox Items collection. Figure 3 The above figure is showing the ListBox control after we have selected the second item and pressed the delete button. Listing 4 private void btnUpload_Click(object sender, System.EventArgs e)
{
int sessionCount = Session.Count
for (int i = sessionCount - 1; i >= 0; i--)
{
if (sessionCount <= 3)
{
HtmlInputFile hif = (HtmlInputFile)Session["myupload" + i];
if (hif.PostedFile.ContentLength <= 500000)
{
string storePath = Server.MapPath("~") + "/MultipleUpload";
if (!Directory.Exists(storePath))
Directory.CreateDirectory(storePath);
hif.PostedFile.SaveAs(storePath + "/" + Path.GetFileName
(hif.PostedFile.FileName));
Label1.Text = "Your Files are uploaded successfully";
ListBox1.Items.Clear();
}
else
Label1.Text = "An error occured";
}
else
Label1.Text =
"You have exceeded the maximum number of files to be uploaded (3)";
}
Session.RemoveAll();
}
The last stage in our code behind is the upload click event. As you can see, the first thing to do is to get the number of the session variables. Because all the selected files are being saved inside session variables, we will loop through all of the sessions to upload its specified file. Note that we are creating a new folder called MultipleUpload where all the files are being saved on the web server. Do not forget to give the write permission for ASPNET user to avoid the access is denied error. After the files have been uploaded, a message will be displayed to inform the user about the upload status. Finally we clear all the items in the ListBox and the session variables. Figure 4 The above figure is showing the final stage when the files have been successfully uploaded. Remember to modify the <httpRuntime maxRequestLength="10000"/> in the web.config to be able to upload files which their size exceeds 4MB. The maxRequestLength value is in KB. In this case, we have modified it to accept the maximum size of 10 MB. |
upload/2007_04/07040908415915.zip