24 September 2013

Uploading a File Using Jsp

The following is the code in html to upload a file.
<form action="xxxServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" />

The following is the code for xxxServlet:-

     String saveFile = "";
     String contentType = request.getContentType();
     if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
           DataInputStream in = new DataInputStream(request.getInputStream());
           int formDataLength = request.getContentLength();
           byte dataBytes[] = new byte[formDataLength];
           int byteRead = 0;
           int totalBytesRead = 0;
           while (totalBytesRead < formDataLength) {
                 byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                 totalBytesRead += byteRead;
           String file = new String(dataBytes);
           saveFile = file.substring(file.indexOf("filename=\"") + 10);
           saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
           saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
           int lastIndex = contentType.lastIndexOf("=");
           String boundary = contentType.substring(lastIndex + 1, contentType.length());
           int pos;
           pos = file.indexOf("filename=\"");
           pos = file.indexOf("\n", pos) + 1;
           pos = file.indexOf("\n", pos) + 1;
           pos = file.indexOf("\n", pos) + 1;
           int boundaryLocation = file.indexOf(boundary, pos) - 4;
           int startPos = ((file.substring(0, pos)).getBytes()).length;
           int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
           saveFile = "C:/himanshu/" + saveFile;
           File ff = new File(saveFile);
           FileOutputStream fileOut = new FileOutputStream(ff);
           fileOut.write(dataBytes, startPos, (endPos - startPos));

If you don’t want to write the code to parse the input stream taken from the request you can use “commons upload” utility provided by apache.

For using commons upload we have to keep the “commons-fileupload.x.x.jar” and “commons-io-x.x.jar” files in the “WEB-APP / lib” folder. These files can be downloaded from http://commons.apache.org/fileupload/ and http://commons.apache.org/io/ .

 The following is the code to place in the xxxServlet:-

 File file ;
int maxFileSize = 5000 * 1024;   
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");

 // Verify the content type
 String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
         DiskFileItemFactory factory = new DiskFileItemFactory();   
         ServletFileUpload upload = new ServletFileUpload(factory);
         // maximum file size to be uploaded.
          upload.setSizeMax( maxFileSize );
               List fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator i = fileItems.iterator();         
              while ( i.hasNext() ){
                   FileItem fi = (FileItem)i.next();
                    if ( !fi.isFormField() ){
     // Get the uploaded file parameters
      String fieldName = fi.getFieldName();
       String fileName = fi.getName();
       boolean isInMemory = fi.isInMemory();
       long sizeInBytes = fi.getSize();    
       // Write the file
      if( fileName.lastIndexOf("\\") >= 0 ){
    file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
    file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                             fi.write( file ) ;
 }//end of if
        }//end of while
    }catch(Exception ex) {

Holding the binary data:-
To hold the binary data we have to use InputStream object. This is the object that can hold large binary data. If you pass the InputStream to Statement.setBlob() that saves the binary data to the database.

Getting the real path of the computer on which server is running:-


Regular Expressions in javascript

When dealing with regular expressions in javascript the following is the way to declare and use them.

Normally in java we declare the regEx as strings.

For example:-

String regEx=”\d{1,3}”;

But in javascript they are no numbers or strings. There is a specific appraoach to declare regEx.

For Example:-

var re5digit=/^\d{5}$/;

In the above the regEx have started  with “/” and also ended with “/”.

Small example for validating input in javascript :-

var re5digit=/^\d{5}$/;
var value=”str123”;
if (value.search(re5digit) == -1) //if match failed
       alert("Please enter a valid 5 digit number inside form");

19 September 2013

Invoking a Filter By Calling a Servlet

If we need to invoke a Filter when calling a particular servlet the following is the snippet for doing as such



So with the above snippet in “web.xml” if we call the “ViewerServlet” the  “ViewerFilter” is automatically executed.

18 September 2013

Getting the hidden element width and height in javascript

Sometimes we might need to get the hidden element width and height. That means when you make the element hidden with css property “display:none”, The element will not render at all. So in this case if we need to get the hidden element height and width we need to make the element position absolute and should make the element x or y value a big negative. So that the element gets rendered but not visible in the html. So that we can get the hidden element height and width.


var calc = document.getElementById("datePicker");
calc.style.left = -1023;
calc.style.display = "block";
var calWidth = calc.offsetWidth;
calc.style.display = "none";

Color Code For Transparency

Sometimes we need the background to be transparent and to do that we need color code for making it transparent.

The color code for transparency is  : #EDEDED

This might work only for images with extension “.png”.