Easy jQuery multifile uploader
I needed a quick and dirty multi-file uploader for a site, but I did not want to install another plugin or a flash uploader. I am using the jQuery form plugin already to handle AJAX form submissions so I will hook to that to upload my files to the site.
My method basically uses jQuery to inject a form with a filefield into the DOM. I bind to the onchange event of the filefield so when a file is added the current file field is hidden, insert a new blank file field, and update a list of queued files waiting to be uploaded. When the user hits the “Upload Files” button, I iterate through all the “input:file” elements using jQuery and submit the form using the jQuery form plugin with ajaxForm(). Of course, you can remove a file from queue as well by clicking on the X in the queue list.
It is an inelegant solution, but it does work. Here is the code if you want to give it a try:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Multi-file upload</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.form.js"></script>
</head>
<body>
<div id="uploadContainer"></div>
<input id="btnSubmit" type="button" value="Submit Files" onclick="submitLoop();" />
<div id="fileInfo"/>
<script language="javascript">
$(document).ready(function(){
$container = $('#uploadContainer');
$info = $('#fileInfo');
count=0;
addUpload();
});
function addUpload(){
count++;
$('form').hide();
$container.append('<form id="uploadForm-' + count +'" action="ajaxProxy.cfc?method=upload" enctype="multipart/form-data"><input id="file-' + count + '" name="filename" type="file" onchange="addUpload();" /></form>');
showFileInfo();
}
function removeItem(id){
if( $('#' + id).length){
$('#' + id).remove();
showFileInfo();
}
}
function showFileInfo(){
$info.html('');
$('input:file').each(function(){
if( $(this).val().length ){
$info.append('<div id="display-' + $(this).attr('id') + '"><a href="#" onclick="removeItem(\'' + $(this).parent().attr('id') +'\')">X</a> ' + $(this).val() + '</div>');
}
});
}
function submitLoop(){
$('input:file').each(function(){
var currItem = $(this).attr('id');
if($(this).val()){
$(this).parent().ajaxForm({
async: false,
success: function(data){
var incoming = $.parseJSON(data);
$('#display-' + currItem).append(' <strong>' + incoming.svrMessage + '</strong>');
}
}).submit();
}
});
}
</script>
</body>
</html>
Recent Comments