473,379 Members | 1,542 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Problem with uploading images using Jsp

118 100+
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.


Expand|Select|Wrap|Line Numbers
  1.  
  2. <%@ page import="java.sql.*" %>
  3. <%@ page import="java.io.*"%>
  4. <%
  5. String connectionURL = "jdbc:mysql://localhost:3306/";
  6. String dbName = "user_register";
  7. Connection connection = null;
  8. PreparedStatement pre=null;
  9. Class.forName("com.mysql.jdbc.Driver").newInstance();
  10. connection = DriverManager.getConnection(connectionURL+dbName, "root", "root");
  11. out.println("connection");
  12. File imgfile = new File("C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/test/Blue.jpg");
  13.  out.println("reerr");
  14.  FileInputStream fin = new FileInputStream(imgfile);
  15.   pre = connection.prepareStatement("insert into Image values(?,?,?)");
  16.   pre.setInt(1,3);
  17.             pre.setString(2,"new");
  18.             pre.setBinaryStream(3,fin,(int)imgfile.length());
  19.             pre.executeUpdate();
  20.             out.println("Inserting Successfully!");
  21.             %>
  22.  
  23.  
Dec 10 '08 #1
11 16101
r035198x
13,262 8TB
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.
Dec 10 '08 #2
ak1dnar
1,584 Expert 1GB
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
Dec 10 '08 #3
chaarmann
785 Expert 512MB
@ak1dnar
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)
Dec 10 '08 #4
swethak
118 100+
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. <%@ page import="java.io.File"%>;
  3. <%@ page import="java.io.FileInputStream"%>;
  4. <%@ page import="java.io.IOException" %>;
  5. <%@ page import="java.sql.Connection"%>;
  6. <%@ page import="java.sql.DriverManager"%>;
  7. <%@ page import="java.sql.PreparedStatement"%>;
  8. <%@ page import="java.sql.ResultSet"%>;
  9. <%@ page import="java.sql.Statement"%>;
  10. <%@ page import="java.util.Iterator"%>;
  11. <%@ page import="java.util.List"%>;
  12. <%@ page import="javax.servlet.ServletException"%>;
  13. <%@ page import="javax.servlet.http.HttpServlet"%>;
  14. <%@ page import="javax.servlet.http.HttpServletRequest"%>;
  15. <%@ page import="javax.servlet.http.HttpServletResponse"%>;
  16. <%@ page import="org.apache.commons.fileupload.*"%>;
  17. <%@ page import="java.sql.*"%>
  18. <%@ page import="java.io.*"%>
  19. <%
  20. String connectionURL = "jdbc:mysql://localhost:3306/";
  21. String dbName = "user_register";
  22. Connection connection = null;
  23. PreparedStatement pre=null;
  24. Class.forName("com.mysql.jdbc.Driver").newInstance();
  25. connection = DriverManager.getConnection(connectionURL+dbName, "root", "root");
  26. out.println("connection");
  27. FileUpload fup = new FileUpload();
  28.             DiskFileUpload upload = new DiskFileUpload();
  29.             List items = upload.parseRequest(request);
  30.             Iterator iter = items.iterator();
  31.  
  32.             int count = 0;
  33.             while (iter.hasNext()) {
  34.                 count++;
  35.                 FileItem item = (FileItem) iter.next();
  36.                 File cfile = new File(item.getName());
  37.                 File tosave = new File(getServletContext().getRealPath("/temp/"), cfile.getName());
  38.                 //item.write(tosave);
  39.                 // String file_name = item.getName(); 
  40.                 FileInputStream fis = new FileInputStream(tosave);
  41.                 int len = (int) tosave.length();
  42.   pre = connection.prepareStatement("insert into Image (image)values(?)");
  43.                 //image_data column holds LONGBLOB data type
  44.  
  45.                  pre.setBinaryStream(1, fis, len);
  46.                 int rows =  pre.executeUpdate();
  47.             }
  48.  
  49.  %>
  50.  
  51.  

errors :


org.apache.jasper.JasperException: 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
Dec 10 '08 #5
ak1dnar
1,584 Expert 1GB
is org.apache.commons.fileupload jar in place? you have to add the relevant jar to the WEB-INF/lib
Dec 10 '08 #6
swethak
118 100+
hi,

i added the commons-fileuploader.jar 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
Dec 10 '08 #7
ak1dnar
1,584 Expert 1GB
Are you telling, your HTML form can upload only the files which is selected from "temp" directory?
Dec 11 '08 #8
swethak
118 100+
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.
Expand|Select|Wrap|Line Numbers
  1. <form name="form-upload" action="POST" action="upload.jsp"  enctype="multipart/form-data">
  2. <input type=file name="ufile">
  3. <input type="submit" name="submit" value="submit">
  4. </form>
  5.  
It works fine. And i added the another filed to form as image name it didn't work. And shows errors

like that

Expand|Select|Wrap|Line Numbers
  1. <form name="form-upload" action="POST" action="upload.jsp"  enctype="multipart/form-data">
  2. Image Name<input type="text" name="imagename" value="">
  3. <input type=file name="ufile">
  4. <input type="submit" name="submit" value="submit">
  5. </form>
  6.  
I used like that i got the error as

Expand|Select|Wrap|Line Numbers
  1. org.apache.jasper.JasperException: Exception in JSP: /upload4.jsp:37
  2.  
  3. 34:             while (iter.hasNext()) {
  4. 35:                 count++;
  5. 36:                 FileItem item = (FileItem) iter.next();
  6. 37:                 File cfile = new File(item.getName());
  7. 38:                 File tosave = new File(getServletContext().getRealPath("/temp/"), cfile.getName());
  8. 39:                 //item.write(tosave);
  9. 40:                 // String file_name = item.getName(); 
  10.  
Stacktrace:
Expand|Select|Wrap|Line Numbers
  1.     org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:504)
  2.     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:393)
  3.     org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
  4.     org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
  5.     javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
  6.  
root cause
Expand|Select|Wrap|Line Numbers
  1. java.lang.NullPointerException
  2.     java.io.File.<init>(Unknown Source)
  3.     org.apache.jsp.upload4_jsp._jspService(upload4_jsp.java:99)
  4.     org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
  5.     javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
  6.     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
  7.     org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
  8.     org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
  9.     javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
  10.  
  11.  
Please tell that solution.How can i modified my code to resolve that 2 problems
Dec 12 '08 #9
ak1dnar
1,584 Expert 1GB
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).

Expand|Select|Wrap|Line Numbers
  1. String name_of_the_file = request.getParameter("imagename");
and then pass that value to your sql statement.
Dec 13 '08 #10
swethak
118 100+
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="multipart/form-data" .please i resolve my problem
Dec 13 '08 #11
i have a problem according to this code
----------uploadImage.jsp-------------------------

--%>
Expand|Select|Wrap|Line Numbers
  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  3.    "http://www.w3.org/TR/html4/loose.dtd">
  4.  
  5. <html>
  6.  
  7. <head><title>Image Upload</title></head>
  8.  
  9. <body>
  10.   <form action="UploadImage" method="post" enctype="multipart/form-data" 
  11.            name="productForm" id="productForm"><br><br>
  12.     <table width="400px" align="center" border=0 style="background-color:ffeeff;">
  13.       <tr>
  14.         <td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">
  15.            Image Details</td>
  16.       </tr>
  17.  
  18.       <tr>
  19.         <td align="center" colspan=2>&nbsp;</td>
  20.       </tr>
  21.  
  22.       <tr>
  23.         <td>Image Link: </td>
  24.         <td>
  25.           <input type="file" name="file" id="file">
  26.         <td>
  27.       </tr>
  28.  
  29.       <tr>
  30.         <td></td>
  31.         <td><input type="submit" name="Submit" value="Submit"></td>
  32.       </tr>
  33.       <tr>
  34.         <td colspan="2">&nbsp;</td>
  35.       </tr>
  36.  
  37.     </table>
  38.   </form>
  39. </body>
  40.  
  41. </html>
  42.  
-----------UploadImage.java-----------------------
*/
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.sql.*;
  3. import java.util.*;
  4. import java.text.*;
  5. import java.util.regex.*;
  6. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  7. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  8. import org.apache.commons.fileupload.*;
  9.  
  10. import javax.servlet.*;
  11. import javax.servlet.http.*;
  12.  
  13. public class UploadImage extends HttpServlet{
  14.   public void doPost(HttpServletRequest request, HttpServletResponse response) 
  15.                 throws ServletException, IOException {
  16.     PrintWriter out = response.getWriter();
  17.     boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  18.     System.out.println("request: "+request);
  19.     if (!isMultipart) {
  20.       System.out.println("File Not Uploaded");
  21.     } else {
  22.       FileItemFactory factory = new DiskFileItemFactory();
  23.       ServletFileUpload upload = new ServletFileUpload(factory);
  24.       List items = null;
  25.  
  26.       try {
  27.         items = upload.parseRequest(request);
  28.         System.out.println("items: "+items);
  29.       } catch (FileUploadException e) {
  30.         e.printStackTrace();
  31.       }
  32.       Iterator itr = items.iterator();
  33.       while (itr.hasNext()) {
  34.         FileItem item = (FileItem) itr.next();
  35.         if (item.isFormField()){
  36.           String name = item.getFieldName();
  37.           System.out.println("name: "+name);
  38.           String value = item.getString();
  39.           System.out.println("value: "+value);
  40.         } else {
  41.           try {
  42.             String itemName = item.getName();
  43.             Random generator = new Random();
  44.             int r = Math.abs(generator.nextInt());
  45.  
  46.             String reg = "[.*]";
  47.             String replacingtext = "";
  48.             System.out.println("Text before replacing is:-" + itemName);
  49.             Pattern pattern = Pattern.compile(reg);
  50.             Matcher matcher = pattern.matcher(itemName);
  51.             StringBuffer buffer = new StringBuffer();
  52.  
  53.             while (matcher.find()) {
  54.               matcher.appendReplacement(buffer, replacingtext);
  55.             }
  56.             int IndexOf = itemName.indexOf("."); 
  57.             String domainName = itemName.substring(IndexOf);
  58.             System.out.println("domainName: "+domainName);
  59.  
  60.             String finalimage = buffer.toString()+"_"+r+domainName;
  61.             System.out.println("Final Image==="+finalimage);
  62.  
  63.             File savedFile = new File("C:/apache-tomcat-6.0.16/webapps/example/"+"images\\"+finalimage);
  64.             item.write(savedFile);
  65.             out.println("<html>");
  66.             out.println("<body>");
  67.             out.println("<table><tr><td>");
  68.             out.println("<img src=images/"+finalimage+">");
  69.             out.println("</td></tr></table>");
  70.  
  71.             Connection conn = null;
  72.             String url = "jdbc:mysql://localhost:3306/";
  73.             String dbName = "thundercatz";
  74.             String driver = "com.mysql.jdbc.Driver";
  75.             String username = "root"; 
  76.             String userPassword = "";
  77.             String strQuery = null;
  78.             String strQuery1 = null;
  79.             String imgLen="";
  80.  
  81.             try {
  82.               System.out.println("itemName::::: "+itemName);
  83.               Class.forName(driver).newInstance();
  84.               conn = DriverManager.getConnection(url+dbName,username,userPassword);
  85.               Statement st = conn.createStatement();
  86.               strQuery = "insert into testimage set image='"+finalimage+"'"; 
  87.               int rs = st.executeUpdate(strQuery);
  88.               System.out.println("Query Executed Successfully++++++++++++++");
  89.               out.println("image inserted successfully");
  90.               out.println("</body>");
  91.               out.println("</html>");            
  92.             } catch (Exception e) {
  93.               System.out.println(e.getMessage());
  94.             } finally {
  95.               conn.close();
  96.             }    
  97.           } catch (Exception e) {
  98.             e.printStackTrace();
  99.           }
  100.         }
  101.       }
  102.     }
  103.   }
  104. }
  105.  
and the error is:
Expand|Select|Wrap|Line Numbers
  1. javax.servlet.ServletException: Servlet execution threw an exception
  2.     org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  3.  
  4. root cause
  5.  
  6. java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
  7.     org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
  8.     org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
  9.     org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
  10.     UploadImage.doPost(UploadImage.java:38)
  11.     javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
  12.     javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
  13.     org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  14.  
  15. root cause
  16.  
  17. java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStream
  18.     org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1360)
  19.     org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1206)
  20.     java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
  21.     org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:196)
  22.     org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:358)
  23.     org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
  24.     UploadImage.doPost(UploadImage.java:38)
  25.     javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
  26.     javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
  27.     org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  28.  
Jun 15 '09 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: laredotornado | last post by:
Hi, I'm using PHP 4 and I am submitting some images in a form with <form name=addProductForm enctype="multipart/form-data" method=post action="add_product_response.php"> <input type=file...
0
by: Terry A. Haimann | last post by:
I have an application, DipperBase, that keeps astronomical images in a mysql database. The actual images are stored in a blob field. To get some test data, I downloaded some SEDS images of...
3
by: Pitcairnia | last post by:
The basic purpose of the site is for authenticated users to post event listings, which often include photographs. The user is faced with a page where they can insert all of the information about...
4
by: Ramakrishnan Nagarajan | last post by:
Hi, I am facing a different problem in my application. In that I am uploading a folder that contain only images. Everything was done and was working fine too. When I executed the application using...
1
by: joe | last post by:
Any articles relating with Uploading images files to server and resize the image by asp.net 2.0
5
by: raji20 | last post by:
Iam uploading some files and images using my code, but the print_r($_FILES) array is coming null Iam using PHP Version 4.3.10 and i have enabled file uploading options in my server ie file_uploads...
1
by: Nerry | last post by:
Hello everyone, I have ASP webpages, but I have a problem uploading my images via ftp, keep getting an error: An error occurred copying a file to the ftp server. Make sure you have permissions...
14
w33nie
by: w33nie | last post by:
What I'm trying to do here, is upload a video to the ../video/ folder, and up to 5 images to the ../images/ folder. As well as the database information like title, content and each file's file...
1
pezholio
by: pezholio | last post by:
Hi, It seems that every time I put together a new script to upload a file I always have problems, here's the latest one: I've got a form with two file input fields, when I submit the form,...
7
by: nwclark | last post by:
Ok... I have a noobie issue. I am trying to upload a photo to specific directory on my server. (this is working correctly with the code below). However, I am also trying to rename the file and...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.