Blob Data files in a zip file using java code - java

I'm trying to add blob data in a zip file. But files are getting corrupted while adding to a zip file. Below code executes, but not zipping the files:
public class BlobDataExtract {
static ZipOutputStream zos = null;
private static ZipOutputStream zosFile;
private static ZipOutputStream zipExtract() throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
java.sql.Blob docBlob = null;
DocumentTO dto = null;
List<DocumentTO> test = new ArrayList<DocumentTO>();
while (rs.next()) {
dto = new DocumentTO();
dto.setDocIndxNb(new Long(rs.getLong(AmpoDBConstants.DOC_INDX_NB)));
dto.setOrigNm(rs.getString(AmpoDBConstants.D_ORIG_NM));
dto.setDocExtNm(rs.getString(AmpoDBConstants.D_DOC_EXT_NM));
docBlob = rs.getBlob(AmpoDBConstants.D_DOC_BO);
// String filepathzipped =rs.getString(AmpoDBConstants.D_ORIG_NM) + ".zip";
InputStream blobStream = docBlob.getBinaryStream();
byte[] newFile = new byte[(int) docBlob.length()];
blobStream.read(newFile);
blobStream.close();
String contentType = "";
String extName = dto.getDocExtNm();
if ("pdf".equalsIgnoreCase(extName))
contentType = "application/pdf";
else if ("html".equalsIgnoreCase(extName) || "htm".equalsIgnoreCase(extName)
|| "stm".equalsIgnoreCase(extName) || "jpeg".equalsIgnoreCase(extName)
|| "jpg".equalsIgnoreCase(extName) || "bmp".equalsIgnoreCase(extName)
|| "gif".equalsIgnoreCase(extName))
contentType = "text/html";
else if ("xls".equalsIgnoreCase(extName) || "xla".equalsIgnoreCase(extName)
|| "xlc".equalsIgnoreCase(extName) || "xlm".equalsIgnoreCase(extName)
|| "xlw".equalsIgnoreCase(extName) || "csv".equalsIgnoreCase(extName)
|| "xlt".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-excel";
else if ("doc".equalsIgnoreCase(extName) || "rtf".equalsIgnoreCase(extName)
|| "rtx".equalsIgnoreCase(extName))
contentType = "application/msword";
else if ("ppt".equalsIgnoreCase(extName) || "pps".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-powerpoint";
else if ("mpp".equalsIgnoreCase(extName))
contentType = "application/vnd.ms-project";
else if ("txt".equalsIgnoreCase(extName))
contentType = "text/plain";
else if ("zip".equalsIgnoreCase(extName))
contentType = "application/zip";
else if ("ics".equalsIgnoreCase(extName))
contentType = "text/calendar";
else if ("snp".equalsIgnoreCase(extName))
contentType = "application/octet-stream";
else
contentType = "text/html";
FileContent fileCont = new FileContent(dto.getOrigNm(), newFile, contentType);
System.out.println("fileCont-->" + fileCont);
dto.setDocBO(fileCont);
test.add(dto);
try {
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream("C:/Users/user/Desktop/test.zip");
zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry(dto.getDocBO().getFullName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes, 0, bytes.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
zos.close();
}
return zos;
}
}
Please help in modifying this code

Your code seems overly complex. It can be reduced to:
public class BlobDataExtract {
private static void zipExtract() throws SQLException, IOException {
String sql = "SELECT ORIG_NM,DOC_EXT_NM,DOC_INDX_NB,DOC_BO FROM zgdt099_document";
try (
Connection conn = DriverManager.getConnection("url", "user", "password");
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:/Users/user/Desktop/test.zip"));
) {
while (rs.next()) {
zos.putNextEntry(new ZipEntry(rs.getString(AmpoDBConstants.D_ORIG_NM)));
zos.write(rs.getBytes(AmpoDBConstants.D_DOC_BO));
}
}
}
}

Issue is resolved with the below code,
public class BlobDataExtract {
static ZipOutputStream zos =null;
static String url = "jdbc:oracle:thin:#hostname:1521:SID";
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, "user", "password");
String sql="select Blob_Data,ORIG_NM from table";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
byte[] docBlob = null;
String filename = null;
FileOutputStream fos = new FileOutputStream("C:/Users/test.zip");
zos = new ZipOutputStream(fos);
while (rs.next()) {
docBlob = rs.getBytes("Blob_Data");
filename = rs.getString("ORIG_NM");
try {
zos.putNextEntry(new ZipEntry(filename));
zos.write(docBlob, 0, Blob_Data.length);
}
catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
}
}

Related

Uploading file using Java Servlet [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a Servlet that uploads an image, and saves the path in a MySQL db. I use the same code for another image upload on a different jsp page, and I get a null pointer exception on "getFileName();"
I do not see any difference in this code. Please help:
addlientimage.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("clientname");
String id = request.getParameter("clientid");
String password = request.getParameter("clientpassword");
String email = request.getParameter("clientemail");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("imageurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("clients.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO clients VALUES ( ?, ?, ?, ?, ? )")) {
clientinfo.setString(1, id);
//setting the first placeholder to the password recieved from the client
clientinfo.setString(2, password);
clientinfo.setString(3, name);
clientinfo.setString(4, url);
clientinfo.setString(5, email);
clientinfo.executeUpdate();
String clients = new PopulateClientsTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("clients", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
addmanager.java
response.setContentType("text/html;charset=UTF-8");
String personName = request.getParameter("mediapersonname");
String productName = request.getParameter("productname");
String mediainfoid = request.getParameter("mediainfoid");
String mediaAbout = request.getParameter("mediaabout");
String personAbout = request.getParameter("personabout");
String productAbout = request.getParameter("productabout");
final String path = getServletContext().getRealPath("/imgs");
final Part filePart = request.getPart("personurl");
final String fileName = getFileName(filePart);
String url = "imgs/" + fileName;
OutputStream outStream;
outStream = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
response.sendRedirect("adminmediainfo.jsp");
try {
outStream = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
outStream.write(bytes, 0, read);
}
Mysqlconnector dbconnect = new Mysqlconnector();
/* TODO output your page here. You may use following sample code. */
try (PreparedStatement clientinfo = dbconnect.getConnection().prepareStatement("INSERT INTO mediainfo VALUES ( ?, ?, ?, ?, ?, ?, ? )")) {
//setting the first placeholder to the password recieved from the client
clientinfo.setString(1, mediainfoid);
clientinfo.setString(2, mediaAbout);
clientinfo.setString(3, personName);
clientinfo.setString(4, productName);
clientinfo.setString(5, productAbout);
clientinfo.setString(6, personAbout);
clientinfo.setString(7, url);
clientinfo.executeUpdate();
String clients = new PopulateMediaInfoTable().getClientRows();
HttpSession session = request.getSession();
session.setAttribute("mediainfo", clients);
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (outStream != null) {
outStream.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
The code for addclientimage.java works. The code for addmanager.java does not.
ERROR LOG
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
AddMediaInfo.getFileName(AddMediaInfo.java:115)
AddMediaInfo.processRequest(AddMediaInfo.java:53)
AddMediaInfo.doPost(AddMediaInfo.java:158)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
I find just two possible reasons for getFileName to throw a NPE:
final String partHeader = part.getHeader("content-disposition");
for (String content : part.getHeader("content-disposition").split(";")) {
Either part is null, so you have to ensure that the caller method is not passing a null to getFileName. I.E.: There exists a "personurl" part within the input request.
Wither partHeader is null, so you have to ensure that the client is actually including a "content-disposition" header within the sent request.

automatically unzip file while downloading that zip file

I have a download button in my webpage where when i click it, it downloads a zip file. now i want to have a function like, when i click the download button the zip file should automatically extract and save in a user defined folder.
i have an idea that if we can create a exe file and add it to the download button then it should automatically extract the zip file and save in folder
%>
<td align="center">
<img onclick="pullReport('<%=reportPath.toString()%>');" title="Click to download this Report" src="./images/down-bt.gif"/>
</td>
</tr>
<%} %>
this is the method that creates zip file
public ActionForward pullReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws SQLException{
Connection connection=null;
boolean cont=false;
failureList.clear();
logger.info("dispatch = pullReport");
String filePaths=null;
String filePath = null;
String fileName = null;
String srcFileName = null;
String directory = null;
try{
Properties props = Application.getProperties();
String basePath = props.getProperty("std.report_location");
logger.info(" basepath " + basePath);
connection=ConnectionManager.getConnection();
StandardReportsForm standardReportsForm=(StandardReportsForm)form;
filePaths=standardReportsForm.getFilePath();
logger.info("filepaths " + filePaths);
ServletOutputStream fos = null;
InputStream is = null;
String [] filePathArr = filePaths.split(",");
FileIO fio = null;
FileIO srcFio = null;
if (filePathArr.length > 1) {
filePath = filePathArr[0].substring(0,filePathArr[0].lastIndexOf("."))+".zip";
logger.info(filePath + " creating zip file ......");
directory = basePath+filePath.substring(0,filePath.lastIndexOf('/'));
logger.info( " Direcory Name :" +directory);
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
logger.info( " File Name :" +fileName);
fio = new FileIO(directory,fileName);
fio.mkDir();
byte[] buffer = new byte[1024];
OutputStream fosForZip = fio.createOutputStream();
ZipOutputStream zos = new ZipOutputStream(fosForZip);
InputStream fis = null;
for (int i=0; i < filePathArr.length; i++) {
srcFileName = filePathArr[i].substring(filePathArr[i].lastIndexOf('/')+1);
srcFio = new FileIO(directory,srcFileName);
if (srcFio.isFileExist()) {
cont=true;
logger.info(" adding into zip file " +srcFileName);
fis = srcFio.createInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(srcFileName));
int length;
while ((length = bis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
bis.close();
srcFio.closeInputStream(fis);
} else {
logger.info(srcFileName + " file does not exist on shared drive");
cont =false;
break;
}
}
FileIO.closeOutputStream(zos);
if (!cont){
standardReportsForm.setMissingFileName(srcFileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
} else {
filePath = filePathArr[0];
fileName = filePath.substring(filePath.lastIndexOf('/')+1);
}
if (basePath.startsWith("smb")) {
SmbFile smbFile = new SmbFile(basePath+filePath,SMBHelper.getInstance().createAuthFromSmbLocation(basePath));
if(smbFile.exists())
{
is = new SmbFileInputStream(smbFile);
cont=true;
}
} else {
File file=new File(basePath+filePath);
if(file.exists())
{
is = new FileInputStream(file);
cont=true;
}
}
if(cont)
{
fos=response.getOutputStream();
setContentType(response, fileName);
//fos.write (baos.toByteArray());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = is.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
byte[] bytes = bos.toByteArray();
fos.write(bytes);
fos.flush();
fos.close();
} else {
standardReportsForm.setMissingFileName(fileName);
request.getSession().getAttribute("fetchReports");
standardReportsForm.setFetchedReports((List<ReportDetails>)request.getSession().getAttribute("fetchReports"));
return mapping.findForward("fetchReport");
}
}catch(SQLException sx) {
logger.error(" error log SQLException " ,sx);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_CONN_EXEC"), sx));
} catch(NamingException ne) {
logger.info("RMI error is "+ne);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_NAMING_EXEC"), ne));
} catch(Exception e) {
logger.error(" error log Exception " ,e);
failureList.add(new UROCException(UROCMessages.getMessage("ERR_GEN_EXEC", new String[] {"General Exception"}), e));
} finally {
SQLHelper.closeConnection(connection, failureList, logger);
}
return null;
}
yah you can use java code to unzip the file.here is the example
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipUtility {
public String zipFilePath= "D:/javatut/corejava/src/zipfile.zip";
public String destDir = "D:/javatut/corejava";
private static final int BUFFER_SIZE = 4096;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
UnzipUtility uu = new UnzipUtility();
uu.unzip(uu.zipFilePath, uu.destDir);
}
public void unzip(String zipFilePath,String destDir)throws IOException{
File destDirectory = new File(destDir);
if(!destDirectory.exists()){
destDirectory.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry zipEntry = zipIn.getNextEntry();
while(zipEntry!=null){
String filePath=destDir+File.separator+zipEntry.getName();
if(!zipEntry.isDirectory()){
extractFile(zipIn,filePath);
}
else{
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
zipEntry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws FileNotFoundException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
thank you.......
please follow this path and (clear) automatic files viewer
chrome://settings/onStartup/Advanced/Downloads/automatic file viewer (clear)

how to read the content of the file and store in database using java

I need to read a file by column and I need to store it in a database. My problem is the file contents are not stored in the database and the code just read the contents. I am getting an error in storing it.
Code:
public class Test3 {
private static String vrms;
private static String irms;
private static String total;
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test3";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username,password);
System.out.println("Connection Established");
return conn;
} catch (Exception e) {
System.out.println("Connection not established");
return null;
} }
public static void main(String[] args) throws Exception {
FileInputStream fstream = new FileInputStream("D:/data/database.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
strLine.split(" ");
System.out.println(strLine);
}
in.close();
FileInputStream fis = null;
PreparedStatement pstmt = null;
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
File file = new File(strLine);
fis = new FileInputStream(file);
pstmt = conn.prepareStatement("insert into meter1(vrms, irms, total) values (?, ?, ?)");
pstmt.setString(1, vrms);
pstmt.setString(2, irms);
pstmt.setString(3, total);
pstmt.executeUpdate();
conn.commit();
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
pstmt.close();
fis.close();
conn.close();
}}}
error:
10 11 0
12 13 0
14 15 0
Connection Established
Error: null
java.lang.NullPointerException
at java.io.File.(Unknown Source)
at vidhya.Test3.main(Test3.java:71)
Exception in thread "main" java.lang.NullPointerException
at vidhya.Test3.main(Test3.java:85)
This is sample code which might be helpful..
Replace the column names with correct db columns.
public static void main(String[] args) throws IOException, SQLException {
PreparedStatement preparedstatement = null;
try{
String read=null;
in = new BufferedReader(new FileReader("patientlist.txt"));
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
name=splited[0];
age=splited[1];
height=splited[2];
weight=splited[3];
addpatient(connection, preparedstatement, name, age, height, weight);
}
}
catch (IOException e) {System.out.println("There was a problem: " + e);}
if (connection != null)
try{connection.close();} catch(SQLException ignore){}
}
public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age, String height, String weight) throws SQLException{
preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
preparedstatement.setString(1, name);
preparedstatement.setString(2, age);
preparedstatement.setString(3, height);
preparedstatement.setString(4, weight);
preparedstatement.executeUpdate();
}
You have not stored information read from the file in any variable (vrms, irms or total). Correct your code before posting here for the issue.
Posting the sample data file and column data types will be helpful.

How to Insert/retrieve Images in SQL server 2008 R2, using Java code?

I work on a java program that needs to insert/retrieve from/to DB (SQL server 2008 R2). Can any one help me?
public void insertImage(Connection conn,String img)
{
int len;
String query;
PreparedStatement pstmt;
try
{
File file = new File(img);
FileInputStream fis = new FileInputStream(file);
len = (int)file.length();
query = ("insert into TableImage VALUES(?,?,?)");
pstmt = conn.prepareStatement(query);
pstmt.setString(1,file.getName());
pstmt.setInt(2, len);
// Method used to insert a stream of bytes
pstmt.setBinaryStream(3, fis, len);
pstmt.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void getImageData(Connection conn)
{
byte[] fileBytes;
String query;
try
{
query = "select data from tableimage";
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery(query);
if (rs.next())
{
fileBytes = rs.getBytes(1);
OutputStream targetFile=
new FileOutputStream(
"d://filepath//new.JPG");
targetFile.write(fileBytes);
targetFile.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

Retrieve an Image stored as BLOB on a MYSQL DB

I'm trying to create a PDF based on the information that resides on a database. Know I need to retrieve a TIFF image that is stored as a BLOB on a mysql database from Java. And I don't know how to do it. The examples I've found shows how to retrieve it and save it as a File (but on disk) and I needed to reside on memory.
Table name: IMAGENES_REGISTROS
BLOB Field name: IMAGEN
Any Ideas?
On your ResultSet call:
Blob imageBlob = resultSet.getBlob(yourBlobColumnIndex);
InputStream binaryStream = imageBlob.getBinaryStream(0, imageBlob.length());
Alternatively, you can call:
byte[] imageBytes = imageBlob.getBytes(1, (int) imageBlob.length());
As BalusC noted in his comment, you'd better use:
InputStream binaryStream = resultSet.getBinaryStream(yourBlobColumnIndex);
And then the code depends on how you are going to read and embed the image.
imagebytes = rs.getBytes("images");
image=getToolkit().createImage(imageBytes);
Image img = image.getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon=new ImageIcon(img);
jLabel6.setIcon(icon);
Try this code to get adjustable image from blog Mysql in netbeans
final String dbURL = "jdbc:mysql://localhost:3306/portfolio";
final String dbUser = "root";
final String dbPass = "";
Connection conn = null;
Statement stmt = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
System.out.println("db connected");
stmt = (Statement) conn.createStatement();
ResultSet rs1;
rs1 = stmt.executeQuery("select profileImage from tbl_welcome where id = 1117");
if (rs1.next()) {
byte[] imgData = rs1.getBytes("profileImage");//Here....... r1.getBytes() extract byte data from resultSet
System.out.println(imgData);
response.setHeader("expires", "0");
response.setContentType("image/jpg");
OutputStream os = response.getOutputStream(); // output with the help of outputStream
os.write(imgData);
os.flush();
os.close();
}
} catch (SQLException ex) {
// String message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void loadFileDataBlobFromDataBase()
{
List<Blob> bFile = jdbcTemplate.query(sql, new RowMapper<Blob>() {
#Override
public Blob mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getBlob(1);
}
});
if (bFile != null && bFile.size() > 0) {
bufReader = new BufferedReader(new InputStreamReader(bFile.get(
0).getBinaryStream()));
}
if (null != bufReader) {
dataVO record = null;
String lineStr = bufReader.readLine();
record = (dataVO) lineMapper.mapLine(lineStr, 1);
}
}
}

Categories