File upload process involves data to be sent from client side to server,
in html terms this means submitting form to server side method that
gets the file from request object and saves it to the server. Most of
the time, it is desirable to implement file upload in ajax way without
refreshing the whole page while updating the user on the progress.
It is a known fact that, it is not possible to do AJAX file uploads to
server using $.ajax or XMLHttpRequest since jquery or javascript does
not support file uploads for security reasons. We are now left out with
two options/workarounds, to use flash or to use hidden iframe. Flash
depends on a plugin to be installed on the user's browser which some
people ans companies don't allow. So, out of the two options, the best
option is to go for hidden iframe solution. This
blog post contains an excellent article on how to do this with plain javascript.
To make the job more easier, let us use this jQuery plugin called
jQuery.AjaxFileUpload.js
which exactly implements the hidden iframe technique behind the scenes
along with progress update and cancelling options. The logic is simple,
instead of submitting the form to the server which would cause a
postback, we submit the contents of the form to an iframe that is
created dynamically and let the iframe communicate with the server, once
the upload is complete - iframe sends the response back to the form.
Steve explains this technique
here in a very neat manner, so I don't want to repeat this here again.
To handle file upload in the server side, let us use Apache Commons File Upload library that makes the job very simple and easy.
1. Download all the required scripts and libraries,
2. Create a dynamic web project in Eclipse. Add the jar files to WEB-INF/lib directory and script files to WebContent folder.
2. Create a jsp file in WebContent and copy paste the below code,
01 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" |
02 | pageEncoding="ISO-8859-1"%> |
03 | http://www.w3.org/TR/html4/loose.dtd |
">
06 | < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > |
07 | < title >Asynchronous file Upload in Java Web Application</ title > |
08 | < script src = "jquery-1.8.2.js" ></ script > |
09 | < script src = "jquery.ajaxfileupload.js" ></ script > |
10 | < script language = "Javascript" > |
11 | $(document).ready(function(){ |
12 | $('input[type="file"]').ajaxfileupload({ |
13 | 'action': 'UploadFile', |
14 | 'onComplete': function(response) { |
16 | alert("File SAVED!!"); |
18 | 'onStart': function() { |
28 | < input type = "file" name = "datafile" /> |
30 | < div id = "upload" style = "display:none;" >Uploading..</ div > |
Note that I have referenced jquery files in the head section of the
html. The execution of script is very simple, whenever a file is
selected using the file browse input, the script gets fired and submits
the selected file to the servlet called 'UploadFile'. The action
parameter takes the servlet url which handles the file upload logic in
the server side. The onStart and onComplete methods are fired while the
file starts to upload and after successful completion of file upload. I
have used these methods to show file upload progress to the user.
3. Now let us use Apache Commons Fileupload library to handle file
upload in the server side. Create a servlet and place the below code in
it.
01 | import java.io.IOException; |
02 | import javax.servlet.ServletException; |
03 | import javax.servlet.annotation.WebServlet; |
04 | import javax.servlet.http.HttpServlet; |
05 | import javax.servlet.http.HttpServletRequest; |
06 | import javax.servlet.http.HttpServletResponse; |
09 | import java.util.Iterator; |
12 | import org.apache.commons.fileupload.FileItem; |
13 | import org.apache.commons.fileupload.FileItemFactory; |
14 | import org.apache.commons.fileupload.FileUploadException; |
15 | import org.apache.commons.fileupload.disk.DiskFileItemFactory; |
16 | import org.apache.commons.fileupload.servlet.ServletFileUpload; |
18 | * Servlet implementation class UploadFile |
20 | @WebServlet ( "/UploadFile" ) |
21 | public class UploadFile extends HttpServlet { |
22 | private static final long serialVersionUID = 1L; |
25 | * Default constructor. |
32 | * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) |
34 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
39 | * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) |
41 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
42 | boolean isMultipart = ServletFileUpload.isMultipartContent(request); |
46 | FileItemFactory factory = new DiskFileItemFactory(); |
49 | ServletFileUpload upload = new ServletFileUpload(factory); |
53 | List items = upload.parseRequest(request); |
54 | Iterator iterator = items.iterator(); |
55 | while (iterator.hasNext()) { |
56 | FileItem item = (FileItem) iterator.next(); |
57 | if (!item.isFormField()) { |
58 | String fileName = item.getName(); |
59 | String root = getServletContext().getRealPath( "/" ); |
60 | File path = new File(root + "/uploads" ); |
62 | boolean status = path.mkdirs(); |
65 | File uploadedFile = new File(path + "/" + fileName); |
66 | System.out.println(uploadedFile.getAbsolutePath()); |
67 | item.write(uploadedFile); |
70 | } catch (FileUploadException e) { |
72 | } catch (Exception e) { |
4. Now the last step is to map the servlet to the action url we have used in index.jsp file as shown below,
02 | < display-name >AjaxFileUpload</ display-name > |
04 | < servlet-name >UploadFile</ servlet-name > |
05 | < servlet-class >com.programmingfree.fileupload</ servlet-class > |
08 | < servlet-name >UploadFile</ servlet-name > |
09 | < url-pattern >/UploadFile</ url-pattern > |
That is all! Now run the application in Tomcat server and upload a file
to see how it gets uploaded without refreshing the whole page.
Once the file is uploaded,
No comments:
Post a Comment