Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Java > Java and JDK > Servlets
|
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 software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old October 29th, 2004, 07:57 AM
Authorized User
 
Join Date: Sep 2004
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.

Thanks.
Pallav
 
Old October 31st, 2004, 03:32 PM
Friend of Wrox
 
Join Date: Jul 2004
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts
Default

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

http://www-106.ibm.com/developerwork...rary/j-jspdwj/

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

http://forum.java.sun.com/thread.jsp...&thread=505366



 
Old October 31st, 2004, 03:39 PM
Friend of Wrox
 
Join Date: Jul 2004
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts
Default

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.

 
Old November 1st, 2004, 01:31 AM
Authorized User
 
Join Date: Sep 2004
Posts: 15
Thanks: 0
Thanked 0 Times in 0 Posts
Default

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 =
    "jdbc:mysql://localhost/javapro";
  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];

        //in.readLine(bytes,0,bytes.length);
        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
            if(line.startsWith("Content-Disposition:"))
            {
                header = parseHeader(line);
                updateParams(header);
                // the Content-Type line tells us the data type
            }
            else if(line.startsWith("Content-Type:"))
            {
                params.put("Content-Type",
                line.substring(
                "Content-Type:".length()).trim());
            }
            else
            {
                // a blank line after the headers tells us we
                // are at the payload
                if(header!=null&&bytes[0]==13)
                {
                    if(header.containsKey("filename"))
                    {

                        String filename = (String)params.get(
                        "filename");
                        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.");
                            return;
                        }
                        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("Height="+height);
                        System.out.println("Size ="+size);

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

                            status=true;
                            onErrRedirect(response);

                        }
                        else
                        {*/

                            savePayload(filename,bin);
                            header = null;
                        //}

                    }
                    else
                    {

                        String name = (String)header.get("name");
                        String value = getParameter(in).trim();
                        params.put(name,value);
                    }
                }
            }
        }

        out.close();


  }
  private void updateParams(Hashtable header){
    for (Enumeration e = header.keys();
      e.hasMoreElements();) {
      String key = (String)e.nextElement();
      params.put(key,header.get(key));
    }
  }
  private String getParameter(
    ServletInputStream in)throws java.io.IOException{
    byte[] bytes = new byte[128];
    in.readLine(bytes,0,bytes.length);
    return new String(bytes);
  }
  private String getBoundary(String contentType){
    int bStart = contentType.indexOf("boundary=")+
      "boundary=".length();
    return "" + CR + LF + "--" +
      contentType.substring(bStart);
  }
  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 );
        saveBlob(filename,blob.toByteArray());
        blob.close();
    }

  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 );
      index++;
    }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));
      index--;
    }
    return input.read();
  }
  private Hashtable parseHeader(String line){
    Hashtable header = new Hashtable();
    String token = null;
    StringTokenizer st = new StringTokenizer(
      line,";");
    while(st.hasMoreTokens()){
      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();
        header.put(key,val);
      }
    }
    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 {
      Class.forName(jdbcDriver);
      con = DriverManager.getConnection(dbUrl,"root","");

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

      con.close();
    }
    catch(ClassNotFoundException e){
      e.printStackTrace();
    }
    catch(SQLException e){
      e.printStackTrace();
    }
  }

}

------------------------------------------

Could u help me out wit this problem?

Thanks.
Pallav
 
Old November 1st, 2004, 05:34 AM
Friend of Wrox
 
Join Date: Jul 2004
Posts: 204
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hello,

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:

http://p2p.wrox.com/topic.asp?TOPIC_ID=20969

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.









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





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