Introduction
This tip tells you how to create a multiple file uploader for ASP.NET with jQuery.
Background
When it comes to uploading different files from different folder locations, existing file uploader can't do that. In this example, we are going to upload multiple files and send email with attachments.
Using the Code
Maximum number of files are determined by the web.config value.
<add key="uploadfilcount" value="5" />
File contents are accessed from HttpFileCollectoin
on Upload button click.
Request.Files
Hidden fields are used to store Maximum uploading file count, Control Index (Index of new control creating) and Uploaded file count.
<asp:HiddenField ID="hdnMaxFile" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="hdnCurrentCtrlIndex" Value="0" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="hdnUploadedFileCount" Value="0" runat="server" ClientIDMode="Static" />
Div
s are used for displaying added file information with remove link, total files uploaded and any validation messages.
<div id="dvFileList"></div>
<div id="dvTotalFiles"></div>
<div id="dvMessage"></div>
Some jQuery scripts handle the upload control creation and removal procedure. Basically, the below script creates a new upload control and adds the new file information to the list with file size in kilobytes. I also wired up uploader removal logic as well. When maximum number of files are uploaded, uploader control is set to hidden.
function AddCtlr() {
var maxFilesCount = $('#hdnMaxFile').val();
var i = parseInt($('#hdnCurrentCtrlIndex').val());
var files = $('#fuMultipleFile' + i).get(0).files;
$("#dvFileList").append("<div class='row'
id=filecontainer" + i + ">
<div class='filename'>" + files[0].name + ' (' +
Math.round(files[0].size / 1024) + ' kb)' +
"</div> <div class='removelink'><a href='#'
onclick=RemoveCtrl(" + i + ");>Remove</a></div>
</div>");
$('#fuMultipleFile' + i).attr("style", "display:none");
var uploadedFilesCount = parseInt($('#hdnUploadedFileCount').val());
uploadedFilesCount = uploadedFilesCount + 1;
$('#hdnUploadedFileCount').val(uploadedFilesCount);
DisplayFileCount(uploadedFilesCount, maxFilesCount);
i = i + 1;
$('#hdnCurrentCtrlIndex').val(i);
if (uploadedFilesCount != maxFilesCount && uploadedFilesCount < maxFilesCount) {
$('#dvUploadContainer').append("<div id='dvCtrl" + i + "'>
<input name='fuCtrl" + i + "'" + "
id='fuMultipleFile" + i + "'" +
" type='file' onchange='AddCtlr();'></div>");
}
}
Below is the file remove logic, if the user clicks the "Remove" link, the corresponding file uploader is removed.
function RemoveCtrl(ctrlindexid) {
$("#fuMultipleFile" + ctrlindexid + "").remove();
$("#dvCtrl" + ctrlindexid + "").remove();
$("#filecontainer" + ctrlindexid + "").remove();
var i = parseInt($('#hdnCurrentCtrlIndex').val());
var maxFilesCount = parseInt($('#hdnMaxFile').val());
var uploadedFilesCount = parseInt($('#hdnUploadedFileCount').val());
if (uploadedFilesCount == maxFilesCount) {
$('#dvUploadContainer').append("<div id='dvCtrl" + i + "'>
<input name='fuCtrl" + i + "'" + " id='fuMultipleFile" + i + "'" +
" type='file' onchange='AddCtlr();'></div>");
}
uploadedFilesCount = uploadedFilesCount - 1;
DisplayFileCount(uploadedFilesCount, maxFilesCount);
$('#hdnUploadedFileCount').val(uploadedFilesCount);
}
The below logic displays footer message like "(2 of 5) files are uploaded".
function DisplayFileCount(uploadedFilesCount, maxFilesCount) {
$('#dvTotalFiles').empty();
$('#dvTotalFiles').append("(" + uploadedFilesCount +
" of " + maxFilesCount + ")" +
" files are uploaded");
$('#dvMessage').empty();
}
The following logic validates at least a file to be present for uploading.
$('#ibUpload').click(function (e) {
if ($("#hdnUploadedFileCount").val() == "0") {
$('#dvMessage').empty();
$('#dvMessage').append("Please upload at least one file");
e.preventDefault();
}
});
Once the Upload button clicks, uploaded file names and files content (stream) are put in to ArrayList
, and process file content to make email attachments and send email. Finally, it redirects to "Thank You" page.
Protected Sub ibUpload_Click(sender As Object, e As EventArgs) Handles ibUpload.Click
Dim UploadedFileList As HttpFileCollection = fuBankStatements.UploadedFiles
Dim filenamelist As New ArrayList
Dim filestreamlist As New ArrayList
Dim currentFileStream As System.IO.Stream
For i As Integer = 0 To UploadedFileList.Count - 1
Dim hpf As HttpPostedFile = UploadedFileList(i)
If hpf.ContentLength > 0 Then
currentFileStream = hpf.InputStream
filestreamlist.Add(hpf.InputStream)
filenamelist.Add(hpf.FileName)
End If
Next i
Me.SendMail(filenamelist, filestreamlist)
currentFileStream.Close()
Response.Redirect("Thankyou.aspx", False)
End Sub
The below function reads the ArrayList
and turns file contents to attachments. Here, we are not creating any files on disk.
Function SendMail(ByVal attachedFilenameList As ArrayList, ByVal streamList As ArrayList) As Boolean
Dim message As New MailMessage(ConfigurationManager.AppSettings("FromMail"), _
ConfigurationManager.AppSettings("ToMail"))
message.Body = "Please check attachments"
message.BodyEncoding = System.Text.Encoding.UTF8
message.IsBodyHtml = True
message.Subject = "Test Mail"
message.SubjectEncoding = System.Text.Encoding.UTF8
If (attachedFilenameList IsNot Nothing And streamList IsNot Nothing) Then
If (attachedFilenameList.Count > 0) Then
For i As Integer = 0 To attachedFilenameList.Count - 1
If (attachedFilenameList(i) <> String.Empty And streamList(i) IsNot Nothing) Then
Dim emailAttachment As New System.Net.Mail.Attachment(DirectCast(streamList(i), _
System.IO.Stream), attachedFilenameList(i).ToString())
message.Attachments.Add(emailAttachment)
End If
Next
End If
End If
Dim mailClient As New SmtpClient(ConfigurationManager.AppSettings("SMTPServer"))
mailClient.Send(message)
Return True
End Function
Points of Interest
In this example, we haven't added any file types, size validations. If you are using any validations, use client side validations instead of server validations. You can get file information by the following scripts. "fuMultipleFile0
" is first upload control and other would be fuMultipleFile1
, fuMultipleFile2
and so on.
$('#fuMultipleFile0').get(0).files