Programming Tutorials

Uploading an Image to a Database using JSP

By: Mahesh in JSP Tutorials on 2010-12-15  

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");






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JSP )

Latest Articles (in JSP)