Uploading an Image to a Database using JSP

By: Mahesh Emailed: 1784 times Printed: 2623 times    

This jsp Page is Uploding The Image into Database using MultipartRequest class FileSystem concepts and ByteArray.

<%@ page import="java.sql.*,java.io.*,java.util.*,com.oreilly.servlet.MultipartRequest,com.microsoft.jdbc.sqlserver.SQLServerDriver;"%>
<%

/* The Following Code is Used To Insert An Image Into Database */

String filename="";
try
{
//Download com.oreilly package

MultipartRequest multi= new MultipartRequest(request,".",5*1024*1024);
Enumeration files=multi.getFileNames();
File f=null;
while(files.hasMoreElements())
{
String name=(String)files.nextElement();
filename=multi.getFilesystemName(name);
String type=multi.getContentType(name);
f=multi.getFile(name);
System.out.println("The File is "+f);
}
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver;databasename="xxx","username","password");
Statement stmt = con.createStatement();
InputStream is = new FileInputStream(f);
byte b[]=new byte[is.available()];
is.read(b);
String sql = "INSERT into photo_test (\"Photo\") values('" + b + "')";
stmt.execute(sql);
stmt.close();
}catch(Exception e)
{
System.out.println(e);
}
out.println("The Image is Added into Database");

Most Viewed Articles (in JSP )

Latest Articles (in JSP)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. java.sql.SQLException: The stream contains more or
View Tutorial          By: Bhawesh Kurmi at 2011-09-03 07:18:04

2. Thanks dude,Its a very simple and helpful code.
View Tutorial          By: Ashutosh Gangrade at 2012-05-02 05:41:18

3. GOOD FOR BIGGENERS
View Tutorial          By: naresh at 2012-08-04 11:19:03

4. good for learners
View Tutorial          By: muhammed at 2012-11-20 10:38:28

5. feel happy but i want to database tables also
View Tutorial          By: sisira at 2013-06-05 13:26:51

6. how to code for images hitting in jsp like googl
View Tutorial          By: Kumaravel at 2014-08-06 11:23:08

7. Robertnaf
View Tutorial          By: Robertnaf at 2017-03-15 11:04:41