i am working with jdbc,mysql,html,jsp.i want to store an image into database through jdbc code and retrive and display them using jsp.please help urgently.I'm creating an online shopping website as a project.
Asked
Active
Viewed 2.4k times
-1
-
Where are the code you already done ? – JGeo Mar 11 '14 at 09:11
-
1Follow the link, you might get some help. http://www.daniweb.com/web-development/jsp/threads/254530/uploading-image-to-mysql-using-htmljsp-form..-need-help – Chandra Prakash Mar 11 '14 at 09:15
1 Answers
1
This is very simple to store an image in MySQL database using JSP :
Go Step By Step:
Step 1- Create this table in database
create table upload_image
(
iImageID int AUTO_INCREMENT primary key,
bImage longblob
);
Step2- Save This code as uploadimage.jsp
<%@ page language="java" errorPage="" %>
<html>
<head>
<title>Image insert into database</title>
</head>
<body>
<form name="frm" action="saveImage.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="uProperty" /> <br>
<input type="submit" name="goUpload" value="Upload" />
</form>
</body>
</html>
Step3- Save This code as saveImage.jsp
<%@ page import="java.sql.*" %>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.io.output.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%
Connection conn=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/gimtech","root", "harit");
PreparedStatement psImageInsertDatabase=null;
byte[] b=null;
try{
String sqlImageInsertDatabase="insert into upload_image (bImage) values(?)";
psImageInsertDatabase=conn.prepareStatement(sqlImageInsertDatabase);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
psImageInsertDatabase.setBytes(1,b);
psImageInsertDatabase.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
response.sendRedirect("addimage.jsp");
}
%>
And you should must add the jar files:
-
-
-
I was just talking about scriptlets in JSP which is highly discouraged for over a decade and should be [avoided](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files/3180202#3180202). – Tiny Mar 11 '14 at 10:26
-
-
Hello, i am creating connection on beans component, but after importing all zip files to `lib`, compiler says: `package org.apache.commons.fileupload.*; does not exists`. – Malwinder Singh Oct 09 '14 at 11:02
-