Problem with uploading images using Jsp

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swethak
    New Member
    • May 2008
    • 118

    Problem with uploading images using Jsp

    Hi,


    My Requirement is to upload the images into database through jsp. For that i write a code .And it works fine .But in that File imgfile = new File("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/test/Blue.jpg"); instead of that i used File imgfile = new File("Blue.jpg" ); like that it didn't work. When we browse that image from local system it automatically takes like Blue.jpg and didn't take the full path.
    So i got the error as " Blue.jpg not found". Please tell the solution how can i resolve my problem.


    Code:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*"%>
    <%
    String connectionURL = "jdbc:mysql://localhost:3306/";
    String dbName = "user_register";
    Connection connection = null;
    PreparedStatement pre=null;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL+dbName, "root", "root");
    out.println("connection");
    File imgfile = new File("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/test/Blue.jpg");
     out.println("reerr");
     FileInputStream fin = new FileInputStream(imgfile);
      pre = connection.prepareStatement("insert into Image values(?,?,?)");
      pre.setInt(1,3);
    			pre.setString(2,"new");
    			pre.setBinaryStream(3,fin,(int)imgfile.length());
    			pre.executeUpdate();
    			out.println("Inserting Successfully!");
    			%>
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    That is not how you attach images using JSPs. Instead you should have a form on your JSP with an input of type file so users can pick the file and upload it. You then need to read that form's request on the server using something like Apache's commons-fileupload.jar.

    P.S Don't connect to databases in JSP code. Do that in a separate class. JSPs are for presentation.

    Comment

    • ak1dnar
      Recognized Expert Top Contributor
      • Jan 2007
      • 1584

      #3
      If you like to use a servlet instead of a jsp file for uploading your files here is an example.
      How to Insert files to MySQL blob using Java Servlet

      Comment

      • chaarmann
        Recognized Expert Contributor
        • Nov 2007
        • 785

        #4
        Originally posted by ak1dnar
        If you like to use a servlet instead of a jsp file for uploading your files here is an example.
        How to Insert files to MySQL blob using Java Servlet
        This sourcecode seems to save a file to disk (the uploaded file), then read this file from disk and then save it to database.
        But why save it on disk first (where everybody can access it, for example a scanned passport) if you want to save it inside the mySql database?

        See my solution in the
        thread titled "Image upload and retrieve from BLOB in jsp"
        how to save it directly into the database. (without saving it to disk first)

        Comment

        • swethak
          New Member
          • May 2008
          • 118

          #5
          Hi,


          Thank you for your reply. I used the jsp code like mentioned that

          When use that code i got the errors. please tell that whats the problem in that.

          Code:
          <%@ page import="java.io.File"%>;
          <%@ page import="java.io.FileInputStream"%>;
          <%@ page import="java.io.IOException" %>;
          <%@ page import="java.sql.Connection"%>;
          <%@ page import="java.sql.DriverManager"%>;
          <%@ page import="java.sql.PreparedStatement"%>;
          <%@ page import="java.sql.ResultSet"%>;
          <%@ page import="java.sql.Statement"%>;
          <%@ page import="java.util.Iterator"%>;
          <%@ page import="java.util.List"%>;
          <%@ page import="javax.servlet.ServletException"%>;
          <%@ page import="javax.servlet.http.HttpServlet"%>;
          <%@ page import="javax.servlet.http.HttpServletRequest"%>;
          <%@ page import="javax.servlet.http.HttpServletResponse"%>;
          <%@ page import="org.apache.commons.fileupload.*"%>;
          <%@ page import="java.sql.*"%>
          <%@ page import="java.io.*"%>
          <%
          String connectionURL = "jdbc:mysql://localhost:3306/";
          String dbName = "user_register";
          Connection connection = null;
          PreparedStatement pre=null;
          Class.forName("com.mysql.jdbc.Driver").newInstance();
          connection = DriverManager.getConnection(connectionURL+dbName, "root", "root");
          out.println("connection");
          FileUpload fup = new FileUpload();
                      DiskFileUpload upload = new DiskFileUpload();
                      List items = upload.parseRequest(request);
                      Iterator iter = items.iterator();
           
                      int count = 0;
                      while (iter.hasNext()) {
                          count++;
                          FileItem item = (FileItem) iter.next();
                          File cfile = new File(item.getName());
                          File tosave = new File(getServletContext().getRealPath("/temp/"), cfile.getName());
                          //item.write(tosave);
                          // String file_name = item.getName(); 
                          FileInputStream fis = new FileInputStream(tosave);
                          int len = (int) tosave.length();
            pre = connection.prepareStatement("insert into Image (image)values(?)");
                          //image_data column holds LONGBLOB data type
           
                           pre.setBinaryStream(1, fis, len);
                          int rows =  pre.executeUpdate();
                      }
          
           %>

          errors :


          org.apache.jasp er.JasperExcept ion: Unable to compile class for JSP

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          FileUpload cannot be resolved to a type

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          FileUpload cannot be resolved to a type

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          DiskFileUpload cannot be resolved to a type

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          DiskFileUpload cannot be resolved to a type

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          FileItem cannot be resolved to a type

          An error occurred at line: 19 in the jsp file: /upload4.jsp
          Generated servlet error:
          FileItem cannot be resolved to a type

          Comment

          • ak1dnar
            Recognized Expert Top Contributor
            • Jan 2007
            • 1584

            #6
            is org.apache.comm ons.fileupload jar in place? you have to add the relevant jar to the WEB-INF/lib

            Comment

            • swethak
              New Member
              • May 2008
              • 118

              #7
              hi,

              i added the commons-fileuploader.ja r in my lib folder.Now it works fine.But i can able to browse the files in temp folder only. If i can browse the other location images it shows the error message as "file not found". Please tell the solution to how i can modify my code according to upload all locations images in my local system

              Comment

              • ak1dnar
                Recognized Expert Top Contributor
                • Jan 2007
                • 1584

                #8
                Are you telling, your HTML form can upload only the files which is selected from "temp" directory?

                Comment

                • swethak
                  New Member
                  • May 2008
                  • 118

                  #9
                  hi


                  Yes.My Problem exactly that one.And also i got another problem with this script.That is

                  when is use like that

                  In that upload.jsp used as above code.
                  Code:
                  <form name="form-upload" action="POST" action="upload.jsp"  enctype="multipart/form-data">
                  <input type=file name="ufile">
                  <input type="submit" name="submit" value="submit">
                  </form>
                  It works fine. And i added the another filed to form as image name it didn't work. And shows errors

                  like that

                  Code:
                  <form name="form-upload" action="POST" action="upload.jsp"  enctype="multipart/form-data">
                  Image Name<input type="text" name="imagename" value="">
                  <input type=file name="ufile">
                  <input type="submit" name="submit" value="submit">
                  </form>
                  I used like that i got the error as

                  Code:
                  org.apache.jasper.JasperException: Exception in JSP: /upload4.jsp:37
                  
                  34:             while (iter.hasNext()) {
                  35:                 count++;
                  36:                 FileItem item = (FileItem) iter.next();
                  37:                 File cfile = new File(item.getName());
                  38:                 File tosave = new File(getServletContext().getRealPath("/temp/"), cfile.getName());
                  39:                 //item.write(tosave);
                  40:                 // String file_name = item.getName();
                  Stacktrace:
                  Code:
                  	org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:504)
                  	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
                  	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
                  	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
                  	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
                  root cause
                  Code:
                  java.lang.NullPointerException
                  	java.io.File.<init>(Unknown Source)
                  	org.apache.jsp.upload4_jsp._jspService(upload4_jsp.java:99)
                  	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
                  	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
                  	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
                  	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
                  	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
                  	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
                  Please tell that solution.How can i modified my code to resolve that 2 problems
                  Last edited by Nepomuk; Dec 12 '08, 11:58 PM. Reason: Added [CODE] tags, although not stricktly needed here, but it's much easier to read.

                  Comment

                  • ak1dnar
                    Recognized Expert Top Contributor
                    • Jan 2007
                    • 1584

                    #10
                    Your question is not that much clear to me.
                    I think you need to POST "imagename" also with your file data.
                    So, first you need to get the POSTed data from your server page (jsp,servlet).

                    Code:
                    String name_of_the_file = request.getParameter("imagename");
                    and then pass that value to your sql statement.

                    Comment

                    • swethak
                      New Member
                      • May 2008
                      • 118

                      #11
                      hi,

                      i passed the field name like that to the next page. It prints the NULL value.

                      We think it is due to by using form attribute like that

                      enctype="multip art/form-data" .please i resolve my problem

                      Comment

                      • farahshafilla
                        New Member
                        • Jun 2009
                        • 1

                        #12
                        i have a problem according to this code
                        ----------uploadImage.jsp-------------------------

                        --%>
                        [code=asp]
                        <%@page contentType="te xt/html" pageEncoding="U TF-8"%>
                        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                        "http://www.w3.org/TR/html4/loose.dtd">

                        <html>

                        <head><title>Im age Upload</title></head>

                        <body>
                        <form action="UploadI mage" method="post" enctype="multip art/form-data"
                        name="productFo rm" id="productForm "><br><br>
                        <table width="400px" align="center" border=0 style="backgrou nd-color:ffeeff;">
                        <tr>
                        <td align="center" colspan=2 style="font-weight:bold;fon t-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">&nb sp;</td>
                        </tr>

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

                        </html>
                        [/code]

                        -----------UploadImage.jav a-----------------------
                        */
                        [code=java]
                        import java.io.*;
                        import java.sql.*;
                        import java.util.*;
                        import java.text.*;
                        import java.util.regex .*;
                        import org.apache.comm ons.fileupload. servlet.Servlet FileUpload;
                        import org.apache.comm ons.fileupload. disk.DiskFileIt emFactory;
                        import org.apache.comm ons.fileupload. *;

                        import javax.servlet.* ;
                        import javax.servlet.h ttp.*;

                        public class UploadImage extends HttpServlet{
                        public void doPost(HttpServ letRequest request, HttpServletResp onse response)
                        throws ServletExceptio n, IOException {
                        PrintWriter out = response.getWri ter();
                        boolean isMultipart = ServletFileUplo ad.isMultipartC ontent(request) ;
                        System.out.prin tln("request: "+request);
                        if (!isMultipart) {
                        System.out.prin tln("File Not Uploaded");
                        } else {
                        FileItemFactory factory = new DiskFileItemFac tory();
                        ServletFileUplo ad upload = new ServletFileUplo ad(factory);
                        List items = null;

                        try {
                        items = upload.parseReq uest(request);
                        System.out.prin tln("items: "+items);
                        } catch (FileUploadExce ption e) {
                        e.printStackTra ce();
                        }
                        Iterator itr = items.iterator( );
                        while (itr.hasNext()) {
                        FileItem item = (FileItem) itr.next();
                        if (item.isFormFie ld()){
                        String name = item.getFieldNa me();
                        System.out.prin tln("name: "+name);
                        String value = item.getString( );
                        System.out.prin tln("value: "+value);
                        } else {
                        try {
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(genera tor.nextInt());

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

                        while (matcher.find() ) {
                        matcher.appendR eplacement(buff er, replacingtext);
                        }
                        int IndexOf = itemName.indexO f(".");
                        String domainName = itemName.substr ing(IndexOf);
                        System.out.prin tln("domainName : "+domainNam e);

                        String finalimage = buffer.toString ()+"_"+r+domain Name;
                        System.out.prin tln("Final Image==="+final image);

                        File savedFile = new File("C:/apache-tomcat-6.0.16/webapps/example/"+"images\\"+fi nalimage);
                        item.write(save dFile);
                        out.println("<h tml>");
                        out.println("<b ody>");
                        out.println("<t able><tr><td>") ;
                        out.println("<i mg src=images/"+finalimage+"> ");
                        out.println("</td></tr></table>");

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

                        try {
                        System.out.prin tln("itemName:: ::: "+itemName) ;
                        Class.forName(d river).newInsta nce();
                        conn = DriverManager.g etConnection(ur l+dbName,userna me,userPassword );
                        Statement st = conn.createStat ement();
                        strQuery = "insert into testimage set image='"+finali mage+"'";
                        int rs = st.executeUpdat e(strQuery);
                        System.out.prin tln("Query Executed Successfully+++ +++++++++++");
                        out.println("im age inserted successfully");
                        out.println("</body>");
                        out.println("</html>");
                        } catch (Exception e) {
                        System.out.prin tln(e.getMessag e());
                        } finally {
                        conn.close();
                        }
                        } catch (Exception e) {
                        e.printStackTra ce();
                        }
                        }
                        }
                        }
                        }
                        }
                        [/code]
                        and the error is:
                        [code=error]
                        javax.servlet.S ervletException : Servlet execution threw an exception
                        org.netbeans.mo dules.web.monit or.server.Monit orFilter.doFilt er(MonitorFilte r.java:390)

                        root cause

                        java.lang.NoCla ssDefFoundError : org/apache/commons/io/output/DeferredFileOut putStream
                        org.apache.comm ons.fileupload. disk.DiskFileIt emFactory.creat eItem(DiskFileI temFactory.java :196)
                        org.apache.comm ons.fileupload. FileUploadBase. parseRequest(Fi leUploadBase.ja va:358)
                        org.apache.comm ons.fileupload. servlet.Servlet FileUpload.pars eRequest(Servle tFileUpload.jav a:126)
                        UploadImage.doP ost(UploadImage .java:38)
                        javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:710)
                        javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:803)
                        org.netbeans.mo dules.web.monit or.server.Monit orFilter.doFilt er(MonitorFilte r.java:390)

                        root cause

                        java.lang.Class NotFoundExcepti on: org.apache.comm ons.io.output.D eferredFileOutp utStream
                        org.apache.cata lina.loader.Web appClassLoader. loadClass(Webap pClassLoader.ja va:1360)
                        org.apache.cata lina.loader.Web appClassLoader. loadClass(Webap pClassLoader.ja va:1206)
                        java.lang.Class Loader.loadClas sInternal(Class Loader.java:319 )
                        org.apache.comm ons.fileupload. disk.DiskFileIt emFactory.creat eItem(DiskFileI temFactory.java :196)
                        org.apache.comm ons.fileupload. FileUploadBase. parseRequest(Fi leUploadBase.ja va:358)
                        org.apache.comm ons.fileupload. servlet.Servlet FileUpload.pars eRequest(Servle tFileUpload.jav a:126)
                        UploadImage.doP ost(UploadImage .java:38)
                        javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:710)
                        javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:803)
                        org.netbeans.mo dules.web.monit or.server.Monit orFilter.doFilt er(MonitorFilte r.java:390)
                        [/code]
                        Last edited by Atli; Oct 14 '10, 07:52 PM. Reason: Please use [code] tags when posting code.

                        Comment

                        Working...