I got this while trying to execute
File f = new File("file location");
FileInputStream fis = new FileInputStream(f);
PreparedStatement ps = db.prepareStatement("INSERT INTO table (title,file,id) VALUES('title',?,7)");
ps.setBinaryStream(1, fis, (int)f.length());
ps.execute();
ps.close();
title - VARCHAR2
file - BLOB
id - FK to another table
Operations with another tables are working, everything is fine but this one. I tried to change statement, drop and recreate table. Without result
Related
I am creating an application where the user can add profiles of different person including his profile picture. However i want to enable the option when there is NO picture to upload. In that way i want to save a default image that it is in package of my project. image in a package of my project
Here is part of the code that i use to save a picture using FileChooser i might be almost the same i think.
String F = TxtRutaFoto.getText();
FileInputStream fis = null;
try{
File file = new File(F);
fis = new FileInputStream(file);
int k = JOptionPane.showConfirmDialog(null, "DESEA GUARDAR LOS DATOS DEL JUGADOR?","PREGUNTA", JOptionPane.YES_NO_OPTION);
if(k == JOptionPane.YES_OPTION){ try (
CallableStatement pstm = conexion.conectar.getConnection().prepareCall("{call INSERTARJUGADOR(?,?,?,?,?,?,?)}")
){
pstm.setString(1, txtID.getText());
pstm.setString(2, txt_ape_pat.getText());
pstm.setString(3, txt_ape_mat.getText());
pstm.setString(4, txt_nombre.getText());
pstm.setString(5, txt_correo.getText());
pstm.setString(6, txt_direc.getText());
pstm.setBinaryStream(7, fis, (int) file.length());
ResultSet r = pstm.executeQuery();
You need to get the InputStream of the picture in your jar. You can do that by using the method classLoader#getResource method:
String loc = getClass().getClassLoader().getResource("/path/to/resource.jpg");
InputStream is = new URL(loc).openStream();
In the default-case you can set that stream instead of the FileInputStream. You should check loc for being null in case the file can't be found (sometimes you have to leave the leading slash away.
Problem solved i used this and its works. First i create a 'resources' folder in where is my default picture. Then i just i used the next code.
File file = new File(getClass().getResource("/resources/user.jpg").getFile());
FileInputStream fis = new FileInputStream(file);
then i just call my procedure
pstm.setBinaryStream(7, fis);
ResultSet r = pstm.executeQuery();
A web app, the client side is jsp and backend is JAVA, DB is simple sqlite.
In the DB there is a table that contains "files" called Reports, and users are allowed to download each file in the DB only ONCE "Due to security requirements", and I have been trying to find a way to do that.
Is there anyway I can write a jsp code that allows the users to download the requested file once from the DB?
I don't know if it is useful but this is the JAVA piece of code that is used to download from the DB.
String sql = "SELECT file, filename FROM reports INNER JOIN download USING(tipid) WHERE reports.tipid = ?"+
"AND download.ts_" + ae_num+ " = 0;";
PreparedStatement stmt = c.prepareStatement(sql);
String tipNum = request.getParameter("tipid");
if (tipNum != null) {
stmt.setString(1, tipNum);
//stmt.setString(2, tipNum);
ResultSet res = stmt.executeQuery();
BufferedInputStream fileBlob = null;
String filename = "";
while (res.next()) {
fileBlob = new BufferedInputStream(res.getBinaryStream("file"), DEFAULT_BUFFER_SIZE);
filename = res.getString("filename");
}
if (fileBlob != null) {
System.out.println(filename);
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = fileBlob.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.close();
fileBlob.close();
Date now = new Date();
sql = "UPDATE download SET ts_" + ae_num + " = " + now.getTime() + " WHERE tipid = ?;";
System.out.println(sql);
stmt = c.prepareStatement(sql);
stmt.setString(1, tipNum);
stmt.executeUpdate();
stmt.close();
c.commit();
c.close();
The current problem I'm having is that whenever a user is trying to download the requested file and whether the user chose to open/save or cancel, it will be counted as a downloaded file, even with a cancel.
Any ideas? Would using cookies in JSP help to implement that? If so can someone guide me? Or how to solve the download count issue
If you have control over the database, you could possibly have another table with the user_id, file_id, download_status column. That way you could always have the records who downloaded the file.
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 have a JSF form where the user uploads data. Now I need to store the file uploaded (could be pdf, doc, xls, etc) into the database. Now of course this file will be loaded later by reviewers. Any idea what is the best way to do this? Serialization? and if yes, any where specific I should look?
I've seen that most serialization deal with user created objects (ones I am familiar with) like employee objects, buildings, etc. But I don't know how to represent the file document as object. as In what to pass to inputReader to get the binary string...
Thanks,
There's no need for serialization at all here - a file is (simplistically) just a name and the data within it. So you just need a name field of type VARCHAR (or whatever) and a data fields of type IMAGE or whatever type your database uses for blobs.
You can use PreparedStatement.setBlob (or potentially PreparedStatement.setBinaryStream; I'll readily admit I'm not confident in the differences) to upload the data.
To insert a binary document into a database you need a table with a column of type BLOB (binary large object).
A skeleton to write:
File f = new File( "your.doc")
FileInputStream fis = new FileInputStream( );
PreparedStatement pstmt = dbCon.prepareStatement("insert into docs(doc) values(?)" );
pstmt.setBinaryStream( 1, fis, (int) l.length() );
pstmt.executeUpdate();
pstmt.close();
to read from the DB:
Statement st = dbCon.createStatement();
ResultSet rs = st.executeQuery("select doc from docs where ..." );
if( rs.next() )
{
InputStream is = rs.getBinaryStream( "doc" );
FileOutputStream fos = new FileOutputStream( "filename" );
// copy is to fos
}
rs.close();
st.close();
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.