Saturday, February 21, 2009

Upload multiple files in HotMail style

Inside class declaration :
static public ArrayList hif = new ArrayList();
public int filesUploaded = 0;

if vb.net
Shared hif_array As New ArrayList

Note : Shared keyword plays a vital role (it allows us to keep the arraylist in memory. And Arraylist helps us to store set of objects.


Add Button
Private Sub Addfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Addfile.Click
If (Page.IsPostBack = True) Then
'checks valid report type and uploads into temprory folder of server
strFileName = Upload1.PostedFile.FileName
FILE_EXTENSION = System.IO.Path.GetExtension(strFileName)
If FILE_EXTENSION = ".doc" Or FILE_EXTENSION = ".ppt" Or FILE_EXTENSION = ".xls" Or FILE_EXTENSION = ".htm" Or FILE_EXTENSION = ".html" Or FILE_EXTENSION = ".mdi" Or FILE_EXTENSION = ".pdf" Then
hif_array.Add(Upload1)
ListBox1.Items.Add(Upload1.PostedFile.FileName)
Else
LBL_Err.Text = "File you have uploaded is not permitted in opsreview. Upload a valid opsreview report"
End If
End If
LBL_Err.Text = hif_array.Count()
End Sub

Remove Button
Private Sub RemFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemFile.Click
If (ListBox1.Items.Count <> 0) Then
hif_array.RemoveAt(ListBox1.SelectedIndex)
ListBox1.Items.Remove(ListBox1.SelectedItem.Text)
End If
End Sub

Upload Button
public void Upload_ServerClick(object sender, System.EventArgs e)
{
string baseLocation = "C:\\temp\\";
string status = "";

if((ListBox1.Items.Count == 0) && (filesUploaded == 0))
{
Label1.Text = "Error - a file name must be specified.";
return;
}
else
{
foreach(System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
{
try
{
string fn = System.IO.Path.GetFileName(HIF.PostedFile.FileName);
HIF.PostedFile.SaveAs(baseLocation + fn);
filesUploaded++;
status += fn + "
";
}
catch(Exception err)
{
Label1.Text = "Error saving file " + baseLocation + "
"
+ err.ToString();
}
}

if(filesUploaded == hif.Count)
{
Label1.Text = "These " + filesUploaded + " file(s) were uploaded:
"
+ status;
}
hif.Clear();
ListBox1.Items.Clear();
}
}

No comments: