my code :
********uploadImage.jsp*************

<form action="UploadImage" method="post" enctype="multipart/form-data" 
           name="productForm" id="productForm"><br><br>
    <table width="400px" align="center" border=0 style="background-color:ffeeff;">
      <tr>
        <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
           Image Details</td>

******UploadImage.java******

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadImage extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("request: " + request);
        if (!isMultipart) {
            System.out.println("File Not Uploaded");
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {
                items = upload.parseRequest(request);
                System.out.println("items: " + items);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    System.out.println("name: " + name);
                    String value = item.getString();
                    System.out.println("value: " + value);
                } else {
                    try {
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(generator.nextInt());

                        String reg = "[.*]";
                        String replacingtext = "";
                        System.out.println("Text before replacing is:-" + itemName);
                        Pattern pattern = Pattern.compile(reg);
                        Matcher matcher = pattern.matcher(itemName);
                        StringBuffer buffer = new StringBuffer();

                        while (matcher.find()) {
                            matcher.appendReplacement(buffer, replacingtext);
                        }
                        int IndexOf = itemName.indexOf(".");
                        String domainName = itemName.substring(IndexOf);
                        System.out.println("domainName: " + domainName);

                        String finalimage = buffer.toString() + "_" + r + domainName;
                        System.out.println("Final Image===" + finalimage);

                        File savedFile = new File("C:/apache-tomcat-6.0.16/webapps/example/" + "images\\" + finalimage);
                        item.write(savedFile);
                        out.println("<html>");
                        out.println("<body>");
                        out.println("<table><tr><td>");
                        out.println("<img src=images/" + finalimage + ">");
                        out.println("</td></tr></table>");

                        Connection conn = null;
                        String url = "jdbc:mysql://localhost:3306/";
                        String dbName = "thundercatz";
                        String driver = "com.mysql.jdbc.Driver";
                        String username = "root";
                        String userPassword = "";
                        String strQuery = null;
                        String strQuery1 = null;
                        String imgLen = "";

                        try {
                            System.out.println("itemName::::: " + itemName);
                            Class.forName(driver).newInstance();
                            conn = DriverManager.getConnection(url + dbName, username, userPassword);
                            Statement st = conn.createStatement();
                            strQuery = "insert into testimage values image='" + finalimage + "'";
                            int rs = st.executeUpdate(strQuery);
                            System.out.println("Query Executed Successfully++++++++++++++");
                            out.println("image inserted successfully");
                            out.println("</body>");
                            out.println("</html>");
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        } finally {
                            conn.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

ERROR :
type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet execution threw an exception
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

root cause

java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
UploadImage.doPost(UploadImage.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

root cause

java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
UploadImage.doPost(UploadImage.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

Include the jar that contains the class "org/apache/commons/io/output/DeferredFileOutputStream" in the WEB-INF/lib directory of your webapp.

tq...but a blank page appears...

Okay? And what does the page source look like (from the browser View --> Source)? Post that here.

<html>

<head><title>Image Upload</title></head>

<body>
  <form action="UploadImage" method="post" enctype="multipart/form-data" 
           name="productForm" id="productForm"><br><br>
    <table width="400px" align="center" border=0 style="background-color:ffeeff;">
      <tr>
        <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
           Image Details</td>
      </tr>

      <tr>
        <td align="center" colspan=2>&nbsp;</td>
      </tr>

      <tr>
        <td>Image Link: </td>
        <td>
          <input type="file" name="file" id="file">
        <td>
      </tr>

      <tr>
        <td></td>
        <td><input type="submit" name="Submit" value="Submit"></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
      </tr>

    </table>
  </form>
</body>

</html>

did u mean this???

Well, that should definately not produce a blank page (unless, maybe, you really are missing that opening "less than" sign). I meant the HTML source of the "blank page" you're talking about.

actually the blank page appears because the image did not save in the database. ..:(

the page is:

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadImage extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("request: " + request);
        if (!isMultipart) {
            System.out.println("File Not Uploaded");
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {
                items = upload.parseRequest(request);
                System.out.println("items: " + items);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    System.out.println("name: " + name);
                    String value = item.getString();
                    System.out.println("value: " + value);
                } else {
                    try {
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(generator.nextInt());

                        String reg = "[.*]";
                        String replacingtext = "";
                        System.out.println("Text before replacing is:-" + itemName);
                        Pattern pattern = Pattern.compile(reg);
                        Matcher matcher = pattern.matcher(itemName);
                        StringBuffer buffer = new StringBuffer();

                        while (matcher.find()) {
                            matcher.appendReplacement(buffer, replacingtext);
                        }
                        int IndexOf = itemName.indexOf(".");
                        String domainName = itemName.substring(IndexOf);
                        System.out.println("domainName: " + domainName);

                        String finalimage = buffer.toString() + "_" + r + domainName;
                        System.out.println("Final Image===" + finalimage);

                        File savedFile = new File("C:/apache-tomcat-6.0.16/webapps/example/" + "images\\" + finalimage);
                        item.write(savedFile);
                        out.println("<html>");
                        out.println("<body>");
                        out.println("<table><tr><td>");
                        out.println("<img src=images/" + finalimage + ">");
                        out.println("</td></tr></table>");

                        Connection conn = null;
                        String url = "jdbc:mysql://localhost:3306/";
                        String dbName = "thundercatz";
                        String driver = "com.mysql.jdbc.Driver";
                        String username = "root";
                        String userPassword = "";
                        String strQuery = null;
                        String strQuery1 = null;
                        String imgLen = "";

                        try {
                            System.out.println("itemName::::: " + itemName);
                            Class.forName(driver).newInstance();
                            conn = DriverManager.getConnection(url + dbName, username, userPassword);
                            Statement st = conn.createStatement();
                            strQuery = "insert into testimage values image='" + finalimage + "'";
                            
                            int rs = st.executeUpdate(strQuery);
                            System.out.println("Query Executed Successfully++++++++++++++");
                            out.println("image inserted successfully");
                            out.println("</body>");
                            out.println("</html>");
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        } finally {
                            conn.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

i think it must be something wrong here.but they are no error..
it makes me going crazy

Actually, there probably are errors, but they are being printed to STDERR

} catch (Exception e) {
    e.printStackTrace();
}

So you need to search your server logfiles.

ooo..ok...
i try to find it...
tq sir
1

how to find to search server logfiles?
i have no idea...

TOMCAT_INSTALATION_DIRECTORY/logs

So if it is local it can be C:\Tomcat 6.0.18\logs or on hosted server just tomcat/logs

What you do not understand? Explain, I'm not mind reader to find out where you failing.

Did you copy a commons-fileupload-1.0.jar into lib folder of your application under WEB-INF?

>What is the datatype of image field?

hi...i have this code.
but i will display blank page when i run it :

import java.io.*;
import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadImage extends HttpServlet{
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
                throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println("request: "+request);
    if (!isMultipart) {
      System.out.println("File Not Uploaded");
    } else {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List items = null;

      try {
        items = upload.parseRequest(request);
        System.out.println("items: "+items);
      } catch (FileUploadException e) {
        e.printStackTrace();
      }
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()){
          String name = item.getFieldName();
          System.out.println("name: "+name);
          String value = item.getString();
          System.out.println("value: "+value);
        } else {
          try {
            String itemName = item.getName();
            Random generator = new Random();
            int r = Math.abs(generator.nextInt());

            String reg = "[.*]";
            String replacingtext = "";
            System.out.println("Text before replacing is:-" + itemName);
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(itemName);
            StringBuffer buffer = new StringBuffer();

            while (matcher.find()) {
              matcher.appendReplacement(buffer, replacingtext);
            }
            int IndexOf = itemName.indexOf("."); 
            String domainName = itemName.substring(IndexOf);
            System.out.println("domainName: "+domainName);

            String finalimage = buffer.toString()+"_"+r+domainName;
            System.out.println("Final Image==="+finalimage);

            File savedFile = new File("C:/apache-tomcat-6.0.16/webapps/example/"+"images\\"+finalimage);
            item.write(savedFile);
            out.println("<html>");
            out.println("<body>");
            out.println("<table><tr><td>");
            out.println("<img src=images/"+finalimage+">");
            out.println("</td></tr></table>");

            Connection conn = null;
            String url = "jdbc:mysql://localhost/thundercatz";
            String dbName = "test";
            String driver = "com.mysql.jdbc.Driver";
            String username = "root"; 
            String userPassword = "";
            String strQuery = null;
          //  String strQuery1 = null;
            //String imgLen="";

            try {
              System.out.println("itemName::::: "+itemName);
              Class.forName(driver).newInstance();
              conn = DriverManager.getConnection(url+dbName,username,userPassword);
              Statement st = conn.createStatement();
              strQuery = "insert into testimage set image='"+finalimage+"'"; 
              int rs = st.executeUpdate(strQuery);
              System.out.println("Query Executed Successfully++++++++++++++");
              out.println("image inserted successfully");
              out.println("</body>");
              out.println("</html>");            
            } catch (Exception e) {
              System.out.println(e.getMessage());
            } finally {
              conn.close();
            }    
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}

farahshafilla,

You already own a thread for the same question.
http://www.daniweb.com/forums/thread197747-2.html

Source code you posted here is a Servlet class. Please post jsp/html code and also write the name/version of your web server.

commented: Well spotted, but next time please report it for faster spotting and resolving issue +19

MERGED

@farahshafilla please read forum rules in regards of posting

farahshafilla,

You said that there is no output - nothing is to be displayed.
--- Use out.println() method instead of System.out.println()

Incorrect insert query statement:
INSERT INTO tablename VALUES ('A','B')

strQuery = "INSERT INTO testimage VALUES ('" + finalimage + "')";
  st.executeUpdate(strQuery);
  out.println("Query Executed Successfully++++++++++++++");
  out.println("image inserted successfully");
  out.println("</body>");
  out.println("</html>");            
      }
       catch (Exception e) {
              out.println(e.getMessage());
      } 
      finally {
              conn.close();
            }    
     }
    catch (Exception e) {
             out.println(e.getMessage());
     }
   ...

i already change the sql statement and also make out.println() method.
but it still display blank page when i run it

Hi,

I want to know the name and version of your webserver.

OK! I have a sample program.

This is a .jsp
index.jsp

<html>
<head><title>Image Upload</title></head>
<% 
 // A message from servlet
 String msg=(String)request.getAttribute("message");
 if(msg==null) msg="";
%>
<body>
  <form action="UploadImage" method="post" enctype="multipart/form-data" 
           name="productForm" id="productForm"><br><br>
    <table width="400px" align="center" border=0 style="background-color:ffeeff;">
      <tr>
        <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
           Image Details</td>
      </tr>
      <tr>
        <td align="center" colspan=2>&nbsp;</td>
      </tr>
      <tr>
        <td>Image Link: </td>
        <td>
          <input type="file" name="file" id="file">
        <td>
      </tr>
      <tr>
        <td colspan="2">
            <%=msg%>
        <input type="submit" name="Submit" value="Submit"></td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
      </tr>
    </table>
  </form>
</body>
</html>

and UploadImage servlet

package com.me;

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
import org.apache.tomcat.jni.Directory;

public class UploadImage extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String message=""; 
       
       // Path,  where uploaded files are to be saved
       String uploaddir=getServletContext().getRealPath("/files");
       String filename="";
       Connection cn=null;
       PreparedStatement st=null;
      try{  
        org.apache.commons.fileupload.DiskFileUpload ds=new DiskFileUpload();
        
        // Parse the request
        List<FileItem> list=ds.parseRequest(request);
        Class.forName("com.mysql.jdbc.Driver");
        cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jaydb","root","root");
        
        // Loop to retrieve form's name-value
        for(FileItem a:list)
        {
            if(a.getContentType()!=null & a.getContentType().startsWith("image/"))
            {
             // Create a directory if it is not exist
             File f=new File(uploaddir);
             f.mkdir();
             // filename from the parsed request
             filename=a.getName();
             
             // Write a record - filename and filedata 
             //   CREATE TABLE `testimage` (
             //  `filename` varchar(100) collate latin1_general_ci NOT NULL,
             //  `filedata` blob NOT NULL
             // ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

             st=cn.prepareStatement("insert into testimage values (?,?)");
             st.setString(1, filename);
             st.setBlob(2,a.getInputStream());
             st.executeUpdate();
             st.close();
                         
             message=" File is uploaded, saved into disk and written into a db. ";
             
             // Save a file into /files folder
             String filePath=uploaddir + "/" + filename;
             FileOutputStream fs=new FileOutputStream(filePath);
             fs.write(a.get());
             fs.close();
            }    
        }
        cn.close();
      }catch(Exception ex)
      {
          request.setAttribute("message", ex.getMessage());
      }
        // Dispatch a request
        request.setAttribute("message",message);
        RequestDispatcher reqDisp=request.getRequestDispatcher("index.jsp");
        reqDisp.forward(request, response);
    }
}

I configured UploadImage servlet - Servlet Mapping
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>UploadImage</servlet-name>
        <servlet-class>com.me.UploadImage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadImage</servlet-name>
        <url-pattern>/UploadImage</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
 </web-app>

and also copy these files -
commons-fileupload-1.0.jar and mysql-connector-java-5.1.5-bin.jar into WEB-INF/lib folder.

adatapos...

i try run your program....
this error appear:

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 22 in the generated java file
The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory

Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:423)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:316)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:294)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:281)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:566)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.

i am using apache as my web server

my web server is apache tomcat and the version is 6.0.16

Which method is used by you to create a web application? - Manual or NetBeans or something else.

Which method is used by you to create a web application? - Manual or NetBeans or something else.

i use netbean 6.1

I am uploading a zip containing the code which I had posted in previous thread. I have use NetBeans6.1. Unzip it, open it uwing netbean6.1, change the mysql - database/user/password and (run)deploy it.

I am uploading a zip containing the code which I had posted in previous thread. I have use NetBeans6.1. Unzip it, open it uwing netbean6.1, change the mysql - database/user/password and (run)deploy it.

still it cannot save in the database.
it is my data base incorrect
my data base is :

CREATE TABLE `testimage` (
  `id` varchar(11) default NULL,
  `image` blob
)

it is my data base incorrect
my data base is :
CREATE TABLE `testimage` (
`id` varchar(11) default NULL,
`image` blob
)

I didn't get you. Are you not creating a table into a database or something else?

At mysql prompt use following commands

>Use database_name
>Create table testimage
(
     imageid varchar(100) primary key,
     imagedata blob
);
>

I didn't get you. Are you not creating a table into a database or something else?

At mysql prompt use following commands

>Use database_name
>Create table testimage
(
     imageid varchar(100) primary key,
     imagedata blob
);
>

i already have my own database.
when i change the database name,username and passwoprd,that u give, the image still not save in the database.so im confused,what's wrong with the code.
it is because of my database or others thing.

Drop the table you have and create a new one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.