View Single Post
  #4 (permalink)  
Old November 1st, 2004, 01:31 AM
Pallav Pallav is offline
Authorized User
 
Join Date: Sep 2004
Location: , , .
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
Reply With Quote