Uploading image to folder & imagepath to database using JSP


Files can be uploaded in multipart/form-data and by doing that the input fields will go null if we use request.getParameter

 To avoid that problem

 Here we have used Apache library for handling file upload together with input fields

  • For this two jars are required: commons-fileupload-1.2.1.jar, commons-io-1.4.jar
  • Download this jars from following link

http://commons.apache.org/fileupload/download_fileupload.cgi

Put this jars file into “WEB-INF\lib” and “C:\Program Files\Java\jre1.6.0\lib\ext”  also.

  • Write (enctype=”multipart/form-data”) in JSP or HTML Page within <form> tag.
<html>
<body>
<form name="form1" method="post" enctype="multipart/form-data" action="insertimage.jsp">

<p>
<input type="file" name="ImageFile" id="ImageFile" />
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</body>
</html>

Here, I have include  “getcon.jsp” in “insertimage.jsp” page to connect a databse in mysql. You can use different database.

code for getcon.jsp

<%@ page import="java.sql.*" %>
<%!Statement st=null;
Connection cn=null;
%>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:data","root","");
<!-- database name= data, username=root, password=blank-->
st=cn.createStatement();
%>

Code for insertimage.jsp

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.*, java.io.*" %>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.File"%>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="getcon.jsp"%> <!-- to connect a database-->

<%
try
{
String ImageFile="";
String itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.getMessage();
}

Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if(name.equals("ImageFile"))
{
ImageFile=value;
}

}
else
{
try
{
itemName = item.getName();
File savedFile = new File("config.getServletContext().getRealPath("/")+"Example\\image-folder\\"+itemName);
item.write(savedFile);
}
catch (Exception e)
{
out.println("Error"+e.getMessage());
}
}
}
try
{
st.executeUpdate("insert into test(image) values ('"+itemName+"')");

}
catch(Exception el)
{
out.println("Inserting error"+el.getMessage());
}
}
}
catch (Exception e){
out.println(e.getMessage());
}
%>

After inserting image Path  into database retrieve image by following JSP code…..

</span>

<%@ include file="getcon.jsp"%>
<html>
<head>
<title>View Image Page</title>
</head>
<body>
<table width="100%" border="0">
<!-- main content -->
<%
ResultSet rs=null;
try
{

rs=st.executeQuery("select image from test");

while(rs.next())
{
%>
<table width="70%" height="160" border="1" align="center">
<tr>
<!-- Mention Directory where your images has been saved-->

<td><img src="image/<%=rs.getString("image") %>" width="115" height="128" /></td>
</tr>
</table>
<%
}
}
catch(Exception e)
{
out.print(""+e.getMessage());
}
%>

</table>
</body>
</html>
<pre>

finally execute your code …………….♣

About these ads

86 Comments (+add yours?)

  1. sai prajeeth
    Jul 17, 2014 @ 13:54:15

    getting error at this line
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    Reply

  2. Dilip Aher
    Jul 21, 2014 @ 16:41:25

    thanks yarr……….really nice……..
    thanks for helping

    File savedFile = new File(“config.getServletContext().getRealPath(“/”)+”Example\\image-folder\\”+itemName);

    error on this line……bt I solve this

    File(config.getServletContext().getRealPath(“/”)+”Example\\image-folder\\”+itemName);

    Reply

  3. Ajit
    Jul 30, 2014 @ 18:33:29

    Thanks sir..
    ur code helps realy much to me,.
    he solved my image uploading problem very easily..
    thanks for,this article

    Reply

  4. Ajit
    Jul 30, 2014 @ 18:42:32

    Because I faced so many problems until this page is,found…

    Reply

  5. Trackback: Fix Commons-io-1.4.jar Errors - Windows XP, Vista, 7 & 8
  6. David.M
    Dec 01, 2014 @ 16:18:38

    Thank you for your Post Sir…

    But i’m facing the below error while running the code,
    i hope the error is related to this Jar files (commons-fileupload-1.2.1.jar, commons-io-1.4.jar), my tomcat version is 7.0.11 and i,m running code using NeatBean-7.0,

    Kindly help me to Fix the Error…..

    Error :
    Compiling 2 source files to D:\Nlag\build\generated\classes
    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:6:
    package org.apache.commons.fileupload.servlet does not exist
    import org.apache.commons.fileupload.servlet.ServletFileUpload;

    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:7:
    package org.apache.commons.fileupload.disk does not exist
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;

    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:8:
    package org.apache.commons.fileupload does not exist
    import org.apache.commons.fileupload.*;

    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:79:
    cannot find symbol
    symbol : variable ServletFileUpload
    location: class org.apache.jsp.insertimage_jsp
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ^
    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:85:
    cannot find symbol
    symbol : class FileItemFactory
    location: class org.apache.jsp.insertimage_jsp
    FileItemFactory factory = new DiskFileItemFactory();

    D:\Nlag\build\generated\src\org\apache\jsp\insertimage_jsp.java:128:
    cannot find symbol
    symbol : variable itemName
    location: class org.apache.jsp.insertimage_jsp
    String myquery=(“insert into test(Image) values(‘”+itemName+”‘)”);

    Reply

    • Ashish Vishwakarma
      Dec 02, 2014 @ 10:40:19

      Hi david,
      Yes, this is bcoz of the particular class are not able to found. so for his u have to add mentioned jar by going to property of this project then go to library.. and add jar there.. or you can write all logic in single class after that call that in action of index.jsp..

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: