| | |
How to save uploaded image in mysql using jsp?
Please support our JSP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
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
So if it is local it can be C:\Tomcat 6.0.18\logs or on hosted server just tomcat/logs
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
What you do not understand? Explain, I'm not mind reader to find out where you failing.
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
hi...i have this code.
but i will display blank page when i run it :
but i will display blank page when i run it :
JSP Syntax (Toggle Plain Text)
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.
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.
Failure is not fatal, but failure to change might be. - John Wooden
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
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')
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')
Jsp Syntax (Toggle Plain Text)
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()); } ...
Failure is not fatal, but failure to change might be. - John Wooden
Hi,
I want to know the name and version of your webserver.
OK! I have a sample program.
This is a .jsp
index.jsp
and UploadImage servlet
I configured UploadImage servlet - Servlet Mapping
web.xml
and also copy these files -
commons-fileupload-1.0.jar and mysql-connector-java-5.1.5-bin.jar into WEB-INF/lib folder.
I want to know the name and version of your webserver.
OK! I have a sample program.
This is a .jsp
index.jsp
Jsp Syntax (Toggle Plain Text)
<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> </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"> </td> </tr> </table> </form> </body> </html>
and UploadImage servlet
Jsp Syntax (Toggle Plain Text)
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
JSP Syntax (Toggle Plain Text)
<?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.
Failure is not fatal, but failure to change might be. - John Wooden
![]() |
Similar Threads
- How to Connect MySQL from JSP Page (JSP)
- Saving n Retrieving Image in mysql (Java)
- Store and retrieve image from mysql db with JSP (JSP)
- how to save and retrieve an image using mysql and php (PHP)
- Problem displaying path of image from mysql (PHP)
- problem saving image into mysql database (VB.NET)
Other Threads in the JSP Forum
- Previous Thread: data file and servlet program
- Next Thread: server deployment in linex with tomacat server
| Thread Tools | Search this Thread |
apache backbutton combobox connection database development directorystructure dynamicpagetitles eclipse frames glassfish imagetodatabse imageupload internet java javaee javascript jsf jsp jsppagetitles levels mvc2 mvcmodel2 network parameters passing ping printinserverinsteadofclient redirect request.getparameter response servlet servletdopost()readxml sessions software ssl state_saving_method stocks sun tomcat tutorial video web






