Posts Tagged ‘fileupload’
How to Upload a File via JQuery AJAX and Read it using Apache Commons
Saturday, November 27th, 2010We had a problem where we needed to upload File to the web based system (JSP) using Ajax Upload. My friend, Jayasanka found this JQuery fix to this problem to get this to the Server and then using Commons Upload we access the uploaded file from Java .
Anyhow, here’s the code:
On The Client Side (JSP/Jquery)
The JQuery plugin that he used is called AjaxFileUpload, which is pretty neat! But a huge flaw in that plugin that we found was that you cannot send other form attributes with that server call, such as a File Description, unless we hack the server URL and append to it and this works!
Apparently this plugin is a Hack of the Ajax Upload. This I haven’t tried. Maybe this solves this problem and it has the other cool options like drag and drop, but thats to be checked out later
<script type="text/javascript" src="<c:url value="/scripts/jquery.js" />"></script>
<script type="text/javascript" src="<c:url value="/fileUpload/ajaxfileupload.js" />"></script>
<script type="text/javascript">
function ajaxFileUpload(){
$("#loading")
.ajaxStart(function(){
$(this).show();
})
.ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload({
url:'<c:out value="/fileUpload.do?exec=uploadFile"/>&desc='$(desc).val(),
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status){
if(typeof(data.error) != 'undefined'){
if(data.error != ''){
alert(data.error);
}
else{
alert(data.msg);
}
}
},
error: function (data, status, e){
alert(e);
}
}) return false;
}
</script>
On The Server Side (Java)
The code of the Current Apache Commons FileUpload which was used in the time of posting (quoting from the documentation) is as follows,
// Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List <FileItem> = upload.parseRequest(request);
We had an Older Version of package where the above classes wasn’t available. This is the code we used:
FileItemFactory itemFactory = new DefaultFileItemFactory(); FileUpload fileUpload = new FileUpload(itemFactory); List<FileItem> files = fileUpload.parseRequest(req.request);
Both of the versions returns FileItems. The first one returns the newer DiskFileItem and the older returns DefaultFileItems, which both has neat methods with mucking around with files



















