This Post explains how to store a picture in an Oracle 10G database. Then It also explains how to retrieve the picture and display it in a web page.The Image is stored in a BLOB.
create table Pictures(PictureName varchar(100) primary key,Picture Blob)
Then download the org.apache.commons.fileupload, and the org.apache.commons.io packages from the Apache website. I bundled it into a jar file, called it org.jar and added it to the lib directory under Tomcat 6.0
Then develop a website and call it PicturesSite, and copy it to the webapps directory in Tomcat 6.0
Then create a resource entry in Context.xml file under the conf directory.
context.xml
<Resource name="Pictures" Auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:XE"
username="system" password="hypatia"
MaxActive="20" MaxIdle="10" MaxWait="-1"/>
Of course the ojdbc14.jar file (It contains the OracleDriver) has to be copied into Tomcat6.0\lib
Here is the code for the PictureUploaderForm. It will upload two pictures at one go.
PicUpload.html
<html>
<body>
<title>FILE UPLOADING</title>
<form id="f1" enctype="multipart/form-data" method="post" action="uploaderservlet">
PICTURE:<input type="FILE" id="picture" name="picture" />
PICTURE:<input type="FILE" id="pictureWa" name="pictureWa" />
<br/>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
uploaderservlet.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class uploaderservlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
response.getWriter().println(con);
PreparedStatement smt=con.prepareStatement("insert into pictures values(?,?)");
/**********************************/
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(100000000);
fu.setSizeThreshold(4096);
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
while(i.hasNext())
{
FileItem fi = (FileItem)i.next();
String filename = fi.getName();
if(filename!=null)
{
response.getWriter().println(filename);
int last=filename.lastIndexOf("\\");
filename=filename.substring(last+1).trim();
String originalfilename=filename;
filename="webapps\\PicturesSite\\images\\" +filename;
File f=new java.io.File(filename);
fi.write(f);
fi.getOutputStream().flush();
fi.getOutputStream().close();
response.getWriter().println("File uploaded successfully" );
smt.setString(1,originalfilename);
FileInputStream fs=new FileInputStream(f);
smt.setBinaryStream(2,fs,(int)f.length());
smt.executeUpdate();
fs.close();
f=null;
}
}
con.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Here is the database after the file uploading is done.
To retrieve the Picture I have used a servlet and written the data to the OutputStream of the response. In a subsequent post I'll explain how to do it via a Java Bean, and a Custom Tag.
Here is the Servlet
showpicture.java
package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class showpicture extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
String name=request.getParameter("picturename");
Context initcontext=new InitialContext();
Context envcontext=(Context)initcontext.lookup("java:/comp/env");
DataSource ds=(DataSource)envcontext.lookup("Pictures");
Connection con=ds.getConnection();
PreparedStatement ps=con.prepareStatement("select picture from pictures where picturename=?");
ps.setString(1,name);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
Blob b=rs.getBlob(1);
OutputStream out=response.getOutputStream();
InputStream in=b.getBinaryStream();
int n=in.read();
while(n!=-1)
{
out.write(n);
n=in.read();
}
out.flush();
out.close();
in.close();
con.close();
}
}
catch(Exception ex)
{
}
}
}
To display the Pictures in an HTML page use the img tag, and send the PictureName via a GET name value pair.
Here is the HTML Page
Pictures.html
<img src="showpicture?picturename=Champak.jpg" alt="Champak.jpg" width="300" height="300"/>
<img src="showpicture?picturename=design.jpg" alt="design.jpg" width="300" height="300"/>
web.xml
<web-app>
<servlet>
<servlet-name>MYFILE</servlet-name>
<servlet-class>servlets.uploaderservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MYFILE</servlet-name>
<url-pattern>/uploaderservlet/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>showimages</servlet-name>
<servlet-class>servlets.showpicture</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showimages</servlet-name>
<url-pattern>/showpicture/*</url-pattern>
</servlet-mapping>
</web-app>
Showing posts with label Blobs. Show all posts
Showing posts with label Blobs. Show all posts
Tuesday, December 14, 2010
Sunday, December 5, 2010
File Uploading, Storing Pictures in MySQL through PHP, and retrieving the Pics.
In this Blog I am endeavoring to provide the basics of file uploading in PHP, storing and retrieving Blobs in MySql through PHP .
First of all lets create a table in MySQL. Here is the Code :-
create database Hypatia;
use Hypatia;
create table Pictures(PictureNo int primary key AUTO_INCREMENT,Picture blob);
The PictureNo column is an auto increment field, this will help us in identifying the newly entered picture.
Create a page having a HTML form with a file control. This form must use the post method, and must have it's encoding type set to multipart/form-data.
Here is the page with the form:-
The file that retrieves the Picture from the database.
First of all lets create a table in MySQL. Here is the Code :-
create database Hypatia;
use Hypatia;
create table Pictures(PictureNo int primary key AUTO_INCREMENT,Picture blob);
The PictureNo column is an auto increment field, this will help us in identifying the newly entered picture.
Create a page having a HTML form with a file control. This form must use the post method, and must have it's encoding type set to multipart/form-data.
Here is the page with the form:-
PicUpload.html
<form id="picform" method="POST" action="PicUpload.php" encType="multipart/form-data">
Select a Picture<input type="file" name="f1" />
<input type="submit"/>
</form>
Select a Picture<input type="file" name="f1" />
<input type="submit"/>
</form>
The File Uploader.
This file receives the uploaded picture from the previous form. The uploaded picture is automatically uploaded to the server and it's path can be accessed through the $_FILES['f1']['tmp_name']; construct where f1 is the name of the file control.$dest=$_FILES['f1']['name']; is the name of the file on the Client. We will copy it using the same name. The move_uploaded_file($src,$dest); copies the file from the source to destination. All files are being stored in the uploads directory. The rest is more or less self explanatory. Any queries are invited.
PicUpload.php
<?php
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$src=$_FILES['f1']['tmp_name'];
print("The file has been uploaded with the temporary name = $src<br/>");
$dest=$_FILES['f1']['name'];
print("The file had the original name = $dest<br/>");
$destpath="uploads/$dest";
$result=move_uploaded_file($src,$destpath);
if($result)
{
print("File Copied<br/>");
print("The copied Picture <img src='$destpath' width='200px' height='200px'/>");
$imagesize=filesize($destpath);
$pic=addslashes(fread(fopen($destpath,"r"),$imagesize));
$queryresult=mysql_query("insert into Pictures values(0,'$pic')");
$NewPicNo=mysql_insert_id();
print("<br/>Picture Inserted successfully");
print("<br/>The Picture from the Database <img src='ShowPic.php?picno=$NewPicNo' width='200px' height='200px'/>");
}
else
print("File not Copied");
?>
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$src=$_FILES['f1']['tmp_name'];
print("The file has been uploaded with the temporary name = $src<br/>");
$dest=$_FILES['f1']['name'];
print("The file had the original name = $dest<br/>");
$destpath="uploads/$dest";
$result=move_uploaded_file($src,$destpath);
if($result)
{
print("File Copied<br/>");
print("The copied Picture <img src='$destpath' width='200px' height='200px'/>");
$imagesize=filesize($destpath);
$pic=addslashes(fread(fopen($destpath,"r"),$imagesize));
$queryresult=mysql_query("insert into Pictures values(0,'$pic')");
$NewPicNo=mysql_insert_id();
print("<br/>Picture Inserted successfully");
print("<br/>The Picture from the Database <img src='ShowPic.php?picno=$NewPicNo' width='200px' height='200px'/>");
}
else
print("File not Copied");
?>
ShowPic.php
<?php
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$picno=$_GET['picno'];
$access=mysql_query("select picture from pictures where pictureno=$picno");
$row=mysql_fetch_row($access);
Header("Content-type:image/jpg");
echo $row[0];
?>
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$picno=$_GET['picno'];
$access=mysql_query("select picture from pictures where pictureno=$picno");
$row=mysql_fetch_row($access);
Header("Content-type:image/jpg");
echo $row[0];
?>
Subscribe to:
Posts (Atom)