I am creating a website with jsp&servlet
and I want to ask :
What's the best way to store an image in a database (mysql) and retrieve it
to using it as profile's picture
And how can i do that?
Thanks you all in advance.
Two common solutions :
directly in the database in a byte field
on the disk, with the path stored in database (I personnaly like to use as name the SHA1 of the file, so I cannot have two times the same file, with the path being a/b/cdef if the SHA1 is abcdef)
Both solutions work very well. The first solution has for advantage to have only one file to backup, to enable rollback, and so on. The second may be more natural as a disk file system is made to store files.
save image in a folder on the server.
save image path in db .
at the time of display get the image path from db and retrieve image.
Store image in database.
import java.sql.*;
import java.io.*;
public class insertImage{
public static void main(String[] args) {
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";;
String dbName = "databasename";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("images.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into Tablename values(?)");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
con.close();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Retrieve image from database using Servlet
http://www.roseindia.net/servlets/retreiveimage.shtml
Related
I'm trying to save an image in Postgresql Database but unable to do that I'm trying to call a function in which I need to Pass image in bytea code.
function to store Image is
CREATE OR REPLACE FUNCTION products_update_image(product_id character varying, img bytea)
RETURNS void AS
'BEGIN UPDATE PRODUCTS SET IMAGE=img::bytea WHERE ID=product_id; END;'
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION products_update_image(character varying, bytea)
OWNER TO postgres;
Answer is very simple for this question. Recently I also worked on this and faced same issue that you are facing, you can use below code.
// Save an image from server to physical location
String destinationFile = "C:\\Program Files (x86)\\openbravopos-2.30.2\\image1.jpg";
// This will call a function which will save an image on your given Location
saveImage(image, destinationFile);
// You don't need to call procedure here just pass this query
PreparedStatement pstmt = con.prepareStatement("UPDATE PRODUCTS SET IMAGE = ? WHERE ID = ?");
// Location of image with it's name
File file = new File("Location\\image1.jpg");
FileInputStream in = new FileInputStream(file);
try
{
pstmt.setBinaryStream(1, in, (int) file.length());
pstmt.setString(2, id);
pstmt.executeUpdate();
}
catch (Exception ee)
{
System.out.println("Exception is:- " + ee);
}
// Function that saved Image on local Location
public static void saveImage(String imageUrl, String destinationFile) throws IOException
{
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1)
{
os.write(b, 0, length);
}
is.close();
os.close();
}
I hope this will work for you as this worked for me
I use derby embedded in a desktop app. But when there is a space in the database path (in any level of directories) the derby driver fails to connect to the database.
Regards, :)
update
public static final String connectionUrl = "jdbc:derby:[path]database;user=app;password=pass;";
String path = Utils.getPathOfJar();
String dbPath = connectionUrl.replace("[path]", path);
dbConnection = DriverManager.getConnection(dbPath);
First of all this problem only occurs in Linux.
The path to the database should be set in the system properties like this:
derby.system.home
like this:
String path = Utils.getPathOfJar();
path = path.jarFilePath.replaceAll("%20", "\\ ");
System.setProperty("derby.system.home", path);
public static final String connectionUrl = "jdbc:derby:database;user=app;password=pass;";
dbConnection = DriverManager.getConnection(connectionUrl);
I am trying to download video file stored as blob in Mysql. The file gets downloaded fine but it gets corrupted i guess. The formats to downloaded are ogg, webm n mp3. The problem is that wen i try to convert any video using ffmpeg, it says "invalid data found during processing".
I am using the following code
Blob image = null;
Connection con = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = MySqlConnect.getDBConnection();
String sql = "select videos, filename from sun.videostore where id ='"+fileID+"'";
Statement stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String filename = rs.getString("filename");
Blob video = rs.getBlob("videos");
File file1 = new File("C:\\DowloadFile\\" + filename);
FileOutputStream foStream = new FileOutputStream(file1);
if( video != null){
int length = (int) video.length();
InputStream is2 = video.getBinaryStream();
int b = 0;
while(b!=-1){
b=is2.read();
foStream.write(b);
}
}
}
}catch(Exception e){
System.out.println("Ecxeption in getting data from DB = "+e);
}'
No i have checked my uploaded file, it is not corrupted....I have tried a different way to upload the video into DB.
File video = new File(filename);
fis = new FileInputStream(video);
ps.setBinaryStream(2, fis, (int) video.length());//preparedStatement
If i upload the file in above way, i get a correct file on downloading.
I'm trying to generate a pdf file from data in a database using JasperReports with a java servlet. The first time I generated a pdf file successfully with data in database. Then I made some changes in my database table and recreated jrxml file and created a jasper file using that jrxml file. But now when I am trying to generate a pdf, the pdf file is always empty.
Code in my Servlet
response.setContentType("application/pdf");
try {
HttpSession hs = request.getSession();
String id = (String) hs.getAttribute("id");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/exam", "root", "pass");
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery
("SELECT marks, date_time FROM result where sub_id = 1 and user_id = 3");
ServletOutputStream set = response.getOutputStream();
InputStream re = getServletConfig().getServletContext().getResourceAsStream("./results.jasper");
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(resultSet);
JasperRunManager.runReportToPdfStream(re,set, new HashMap(), resultSetDataSource);
} catch (Exception e) {
}
How could I solve this?
Change every catch to
...
} catch (Exception e) {
e.printStackTrace();
}
That will provide details of what is going wrong, and where.
I am looking for a good example of upload & download file to/from Oracle database in Java to get idea. Would you please help me if any of you know a good example?
Here for upload:
public class FileToDatabase {
public static void main(String[] args) throws Exception {
String fileName = "C:/input.txt";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement pstmt = conn
.prepareStatement("insert into file( file, file_data) values ( ?, ?)");
pstmt.setString(1, file.getName());
pstmt.setBinaryStream(2, fis, (int) file.length());
pstmt.executeUpdate();
}
Here for download
I found a good piece of code for file downloading from an application server, (in the link below).
If you are going to use a web app, you could cache the file from the database into the application before the download.(Im interested in what other thinks about this alternative)
Link: http://www.daniweb.com/software-development/java/threads/154128