Friday, February 15, 2013

Dynamic File Upload in JSP, without refreshing, using Ajax and jQuery

We have already covered a tutorial for Dynamic file upload in Php, and as now we have also started covering JSP and Advanced Java in our Tutorials, so we made this script using JSP and Servlet too for the web developers who develop using JSP. In this Script we have used jQuery and Ajax for making the Upload Dynamic. We have also used Part Interface of Java.
We have used the NetBeans 7.0 IDE for developing this application, you can use any IDE which you want. You just need to make the JSP files, Servlets and Java Class enclosed in the Download File.

css
  • style.css
js
  • jquery.form.js
  • jquery-1.7.1.min.js
Java Class
  • FileName.java
Servlet
  • displayImage.java

JSP Files : file_upload.jsp , ajax_file.jsp 



Download the Script



In this script we just have implemented how to upload file and preview it without refreshing the page. Database connectivity is not included, but you can very easily save the uploaded file's name into database by using a simple prepared statement to do that.


  file_upload.jsp :  


//Include these two jquery files
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
//script to display the preview of uploaded file
<script type="text/javascript" >
$(document).ready(function() 

$('#photoimg').change(function()
{
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});}); 
</script>
//Form to upload file or image
<form action="ajax_upload.jsp" id="imageform" method="post" enctype="multipart/form-data">
Upload image from your computer : <input type="file" id="photoimg" name="photoimg"/>
</form>
//div to display uploaded file
<div id='preview'></div>


  ajax_file.jsp :  


<%@page import="model.*;" %>   //Include Java Class in the model package

<%! OutputStream fout = null;
    InputStream filecontent = null
    String type="";
%>
<%
final String path ="d:/myfolder/";  //Location of upload folder
final Part filePart = request.getPart("photoimg");
//get content type of the file
type=filePart.getHeader("content-type");

//checking content type of file. 
if( type.equals("image/jpeg") || type.equals("image/png") ||
 type.equals("image/jpg") || type.equals("image/gif") ||
type.equals("image/bmp") )
{
final String fileName = FileName.getFileName(filePart);
//copy the content of the file
try {
fout = new FileOutputStream(new File(path + File.separator + fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[32*1024];
while ((read =filecontent.read(bytes)) != -1) {
fout.write(bytes, 0, read);
}
fout.flush();
fout.close();
%>
%lt;!-- displayImage is the name of the servlet which will read the image file and set it on response object-->
<img src="displayImage/<%=fileName%>" />
<% } catch (Exception e) { %>
<div style="font-size:30px; color:red">File is not successfully uploaded</div>
<% } } else { %<
<div style="font-size:30px; color:red">Please upload image(jpeg,jpg,gif,bmp,png) file only</div>
<% } %>

Apart from these two jsp pages you will have to make a Java package, in that package create a Java class file, named FileName.java and a servlet outside the model package named displayImage.java file.

Copy the content of Java Class file and servlet into these files respectively. Create a new folder for uploads, where the images/files will be uploaded and copy-paste its address in path variable in ajax_file.jsp file.


  web.xml :  


<servlet>
<servlet-name>displayImage</servlet-name>
<servlet-class>displayImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>displayImage</servlet-name>
<url-pattern>/displayImage/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>file_upload.jsp</welcome-file>
</welcome-file-list>


For any problem, do feel free to comment, we will try our best to help you out. And do comment and share this post with your friends. We will be coming up with more tutorials for JSP soon.


12 comments:

  1. hi sir here is the error i get when running
    exception

    org.apache.jasper.JasperException: An exception occurred processing JSP page /ajax_file.jsp at line 18

    15: final String path ="D:/myfolder/";
    16: final Part filePart = request.getPart("photoimg");
    17: //return content type of the file
    18: type=filePart.getHeader("content-type");
    19: System.out.println(type);
    20: //checking content type of file.
    21: if(type.equals("image/jpeg") || type.equals("image/png") || type.equals("image/jpg") || type.equals("image/gif") || type.equals("image/bmp") )


    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    cause mère

    java.lang.NullPointerException
    org.apache.jsp.ajax_005ffile_jsp._jspService(ajax_005ffile_jsp.java:76)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    ReplyDelete
  2. final Part filePart = request.getPart("photoimg"); this line shows error that getPart is not available at http request object.
    please help

    ReplyDelete
  3. org.apache.jasper.JasperException: An exception occurred processing JSP page /ajax_file.jsp at line 18

    15: final String path ="D:/myfolder/";
    16: final Part filePart = request.getPart("photoimg");
    17: //return content type of the file
    18: type=filePart.getHeader("content-type");
    19: System.out.println(type);
    20: //checking content type of file.
    21: if(type.equals("image/jpeg") || type.equals("image/png") || type.equals("image/jpg") || type.equals("image/gif") || type.equals("image/bmp") )


    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    cause mère

    java.lang.NullPointerException
    org.apache.jsp.ajax_005ffile_jsp._jspService(ajax_005ffile_jsp.java:76)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    ReplyDelete
    Replies
    1. Sorry for replying late,
      Check for the following - Have you made a folder named "myfolder" in D drive ?
      or if Part class is included and working fine ?

      Delete
    2. Hi.. I used this code.. I am also facing the same error.. i checked using your solution and they are there.. Still it isn't working.. Pls help...

      Delete
  4. Source: http://www.coderanch.com/t/580782/Servlets/java/request-getPart-Tomcat

    posted 5/12/2012 9:36:04 AM purple mooseage Quote
    I solved the problem. I edit the file context.xml (tomcat->conf). You need to edit it, putting the attribute allowCasualMultipartParsing="true" in the tag , and then you have: . Restart the server and it works.

    ReplyDelete
  5. can we edit context.xml on actual server?? i am facing same problem.i could not upload a file on actual server..when i uploading image file on temporary server getting this error but in case of local machine it is working fine..

    ReplyDelete
  6. have you slove this problem, I am facing same probelm, please help me

    ReplyDelete
  7. thanks billson chew its working now but when i use it to upload audio or video files it is giving error on this line final Part filePart = request.getPart("photoimg");
    i would be greatful if u could help me
    HTTP Status 500 - An exception occurred processing JSP page /ajax_file.jsp at line 16

    type Exception report

    message An exception occurred processing JSP page /ajax_file.jsp at line 16

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: An exception occurred processing JSP page /ajax_file.jsp at line 16

    13: <%
    14:
    15: final String path ="e:/myfolder/";
    16: final Part filePart = request.getPart("photoimg");
    17: //return content type of the file
    18: //type=filePart.getHeader("content-type");
    19: //System.out.println(type);

    ReplyDelete
  8. I am facing the same issue.Already applied the fix,but it didn't worked...please help!

    ReplyDelete
  9. I am facing this error
    java.lang.IllegalStateException: Request.getPart is called without multipart configuration. Either add a @MultipartConfig to the servlet, or a multipart-config element to web.xml
    please help me

    ReplyDelete
  10. java.lang.IllegalStateException: Request.getPart is called without multipart configuration. Either add a @MultipartConfig to the servlet, or a multipart-config element to web.xml
    ihave configured the web.xml but then also getting error

    ReplyDelete