Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Java and JDK > Servlets
Password Reminder
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Servlets section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old October 29th, 2004, 07:57 AM
Authorized User
Join Date: Sep 2004
Location: , , .
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default uploading Images..

Hi all,
I want to upload images to a mysql db as blob data type..

The image is uploaded by the following steps..

1.An html form (say upload_image.jsp)
 using <input type="file"> tag.
This form is used to select the image to be uploaded.
This form submits to a servlet say "UploadServlet.java".

2.The UploadServlet reads the post data
which is sent by upload_image.jsp and inserts the required
image data into the database.

How do i restrict the height,width and size of the image that is
being uploaded??

Could anybody please help me out.

Reply With Quote
  #2 (permalink)  
Old October 31st, 2004, 03:32 PM
Friend of Wrox
Join Date: Jul 2004
Location: , , .
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts

Check this out, i used it to create thumbnails to add to my database:


Furthemore the following link provides excellent code for watermarking and overlaying images.


Reply With Quote
  #3 (permalink)  
Old October 31st, 2004, 03:39 PM
Friend of Wrox
Join Date: Jul 2004
Location: , , .
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts

Hello again, think I may have misread your question, the link I gave allows you to resize images once they are on your server. I dont think there is a way to stop over sized (by dimension) images being uploaded, there may be a way to do it by file size (bytes) though.

Reply With Quote
  #4 (permalink)  
Old November 1st, 2004, 01:31 AM
Authorized User
Join Date: Sep 2004
Location: , , .
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts

Hi angrycat,
Thnx for replying.

I m able to get image height and width in my UploadServlet.java
(using an image class from http://www.geocities.com/marcoschmid...mage-info.html)

The post data from Upload.jsp is provided as a ServletInputStream object
to the image class.

However this same ServletInputStream object is also required to save the image into the database.

Using the same ServletInputStream object is not possible for doing both the tasks of checking image size and saving the image to the database.

The code for UploadServlet.java is as below:

package classlib.upload;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import classlib.multimedia.image.*;

public class UploadServlet extends HttpServlet{
  private String dbUrl =
  private String jdbcDriver = "com.mysql.jdbc.Driver";

  private static final char CR = 13;
  private static final char LF = 10;
  private boolean status = false;

  protected String boundary = null;
  protected Hashtable params = new Hashtable();
  protected ServletOutputStream out = null;

  public void doPost( HttpServletRequest request,HttpServletResponse response )
    throws ServletException, IOException
        out = response.getOutputStream();
        ServletInputStream in = request.getInputStream();
        ServletInputStream in2 = request.getInputStream();

        BufferedInputStream bin = new BufferedInputStream(in);

        boundary = getBoundary(request.getHeader("content-type"));

        byte[] bytes = new byte[128];

        String line = new String(bytes);
        System.out.println("line ="+line);
        Hashtable header = null;
        while((in.readLine(bytes,0,bytes.length)>=0)&&(!st atus))
            line = new String(bytes);

            // the Content-Disposition line gives us the
            // filename
                header = parseHeader(line);
                // the Content-Type line tells us the data type
            else if(line.startsWith("Content-Type:"))
                // a blank line after the headers tells us we
                // are at the payload

                        String filename = (String)params.get(
                        out.println("Saving "+filename);

                                                //This is where i check the image size
                        ImageInfo ii = new ImageInfo();
                        ii.setInput(in2); // in2 can be InputStream or RandomAccessFile
                        ii.setDetermineImageNumber(true); // default is false
                        ii.setCollectComments(true); // default is false
                        if (!ii.check())
                            System.out.println("Not a supported image file format.");
                        System.out.println(ii.getFormatName() + ", " + ii.getMimeType() +
                           ", " + ii.getWidth() + " x " + ii.getHeight() + " pixels, " +
                           ii.getBitsPerPixel() + " bits per pixel, " + ii.getNumberOfImages() +
                           " image(s), " + ii.getNumberOfComments() + " comment(s).");

                        int width=ii.getWidth();
                        int height=ii.getHeight();
                        int size=width*height*ii.getBitsPerPixel();

                        System.out.println("Width ="+width);
                        System.out.println("Size ="+size);

                        /*if ((width>100)||(height>100))
                            System.out.println("File size 2 large");



                            header = null;


                        String name = (String)header.get("name");
                        String value = getParameter(in).trim();


  private void updateParams(Hashtable header){
    for (Enumeration e = header.keys();
      e.hasMoreElements();) {
      String key = (String)e.nextElement();
  private String getParameter(
    ServletInputStream in)throws java.io.IOException{
    byte[] bytes = new byte[128];
    return new String(bytes);
  private String getBoundary(String contentType){
    int bStart = contentType.indexOf("boundary=")+
    return "" + CR + LF + "--" +
  private void savePayload(String filename,BufferedInputStream is)
    throws java.io.IOException
        int c;
        System.out.println("In savePayload");
        System.out.println("Payload I-stream ="+is);
        PushbackInputStream input = new PushbackInputStream(is,128);
        ByteArrayOutputStream blob = new ByteArrayOutputStream();
        while ( (c=read(input,boundary)) >=0 )
            blob.write( c );

  private int read( PushbackInputStream input,
    String boundary )
  throws IOException
    StringBuffer buffer = new StringBuffer();
    int index = -1;
    int c;

    do {
      c = input.read();
      buffer.append( (char)c );
    }while ( (buffer.length() < boundary.length()) &&
      (c == boundary.charAt(index)) );

    if ( c == boundary.charAt(index) ){
      int type = -1;
      if ( input.read() == '-' )
        type = -2;
      while ( input.read() != LF );
      return type;

    while ( index >= 0 ){
      input.unread( buffer.charAt(index));
    return input.read();
  private Hashtable parseHeader(String line){
    Hashtable header = new Hashtable();
    String token = null;
    StringTokenizer st = new StringTokenizer(
      token = ((String)st.nextToken()).trim();
      String key = "";
      String val = "";
      int eq = token.indexOf("=");
      if(eq <0) eq = token.indexOf(":");
      if(eq >0){
        key = token.substring(0,eq).trim();
        val = token.substring(eq+1);
        val = val.replace('"',' ');
        val = val.trim();
    return header;
  private void saveBlob(String filename,byte[] out){
    Connection con = null;
    PreparedStatement pstmt = null;
    //String sqlCmd =
      //"update BLOBS set FileName=?,BinaryData=? where id=1";
    String sqlCmd = "insert into BLOBS (FileName,BinaryData) values(?,?)";
    try {
      con = DriverManager.getConnection(dbUrl,"root","");

      pstmt = con.prepareStatement(sqlCmd);
      pstmt.setString(1, filename);
      pstmt.setBytes(2, out);

    catch(ClassNotFoundException e){
    catch(SQLException e){



Could u help me out wit this problem?

Reply With Quote
  #5 (permalink)  
Old November 1st, 2004, 05:34 AM
Friend of Wrox
Join Date: Jul 2004
Location: , , .
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts


You could have a look at this thread on a similar subject, has some code snippets I posted that show in brief how I uploaded images to my database:


I see at one point you have data in a BinaryInputStream, so Ill start there:

// fileBytes was the byteArray I read data into from the POST method
bin = new ByteArrayInputStream( fileBytes, 2, offset-2 );

// necessary to convert ByteArrayInputStream to InputStream
InputStream is = bin;

// setBinaryStream is the only way I have found to put a Blob
// into the database, and it will only take a standard InputStream.

pstmt.setBinaryStream( 5, is, (int)(len));

You should be able to run your code to check the size of the image before converting the data type to an InputStream for uploading to the database.

I have done something similar which watermarked an image with a URL, saved it to the database, then resized it to a thumbnail and saved this also.

Reply With Quote

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
error in uploading images poojagupta Classic ASP Basics 0 November 6th, 2007 04:35 AM
uploading, retrieving images kourosh Classic ASP Basics 2 September 17th, 2005 04:33 PM
uploading images to server joseph007 Classic ASP Components 0 September 16th, 2004 08:30 AM
Uploading images to a database vivi Classic ASP Basics 3 October 30th, 2003 10:14 PM

All times are GMT -4. The time now is 07:57 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.