Tuesday, September 9, 2014

Dynamic file uploading in JSP, without refreshing, using Ajax and Jquery

In this post we will show you how to upload File/Image in JSP dynamically i.e without refreshing the pageusing ajax and jquery. This post will enable to upload a image to the server and display the same image on the page itself without refreshing the page. There are several different way to implement this but we have tried to show you the most cleanness and simplest one.You can use the same code for uploading file also.








file_upload.jsp

//import this two jquery-library.
<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 image
<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>


on upload




ajax_file.jsp
<%@page import="java.io.*,java.sql.*,model.*;" %>

<%! OutputStream fout = null;
    InputStream filecontent = null; 
    String type="";
%>

<%

final String path ="d:/myfolder/";
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();
%>

<!-- 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>");

<% } %>


FileName.java

This class contains a method getFileName( ) which will return the name of file uploaded. 

package model;
import java.io.*;
import javax.servlet.http.Part;

 public class FileName {
         
  //this method return name of file uploaded
 public static String getFileName(final Part part) {
   
for (String content : part.getHeader("content-
               disposition").split(";")) 
   {
     if (content.trim().startsWith("filename")) {
       return content.substring
       (content.indexOf('=')+1).trim().replace("\"", "");
          
            }
        }
        return null;
    } 
}


displayImage.java

We have create a servlet to read the uploaded image from target folder, and set it on response object to display it.

import java.io.*;
import java.net.URLDecoder;
import javax.servlet.*;
import javax.servlet.http.*;


public class displayImage extends HttpServlet {

    private static final int DEFAULT_BUFFER_SIZE = 10240; 
    private String imagePath;

    public void init() throws ServletException {

        this.imagePath = "d:/myfolder"; //target path

 }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        // Get requested image by path info.
        
    String requestedImage = request.getPathInfo();

    // Check if file name is actually supplied to the request URI.
        if (requestedImage == null) {

 // Do your thing if the image is not supplied to the request URI.
  

response.sendError(HttpServletResponse.SC_NOT_FOUND); 
            return;
        }

        // Decode the file name (might contain spaces and on) and prepare file object.
        
File image = new File(imagePath,URLDecoder.decode
                         (requestedImage, "UTF-8"));

        // Check if file actually exists in filesystem.


        // Get content type by filename.
    String contentType =
           getServletContext().getMimeType(image.getName());


        // Init servlet response.
     response.reset();
     response.setBufferSize(DEFAULT_BUFFER_SIZE);
     response.setContentType(contentType);
     response.setHeader("Content-Length",
                         String.valueOf(image.length()));
    response.setHeader("Content-Disposition", "inline;
                     filename=\"" + image.getName() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            close(output);
            close(input);
        }}

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                 e.printStackTrace();
            } }
    }
}




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>

ref: http://www.programdiary.in/2013/02/fileuploading.html

No comments:

Post a Comment