Download blob data in a zip file in a simple java program - java

I'm not able to download the files using the below code as i have multiple types of extensions to download and i want to zip all the files and download. If i run the below code, it says files is corrupted. someone please help on this?
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcReadFile {
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
String url = "jdbc:oracle:thin:#xxx:xxxx:xxx";
String user = "xxx";
String password = "xxx";
String filePath = "C:/abc.vsd";
try {
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "SELECT DOC_BO FROM table fetch first 10 rows only";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("DOC_BO");
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
System.out.println("File saved");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

No front end is required for this. Issue is resolved using 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, docBlob.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

How to retrieve an zip file from oracle blob using java?

I have an zip file stored in an Oracle database table which is consisting of three different xml files. What I'm trying to do is get this zip file in my local file system. To retrieve this zip file I have written below java code:
package com.pack.IOT;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test2 {
public static Connection con;
public static PreparedStatement stmt;
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,uname,pwd);
stmt=con.prepareStatement("select * from FileStore");
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
InputStream is = rs.getBinaryStream(3);
convert(is);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void convert(InputStream is) {
FileOutputStream outputStream = null;
File file = new File("C:\\Users\\nshaik\\Desktop\\IOTZip.zip");
try {
outputStream = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result;
result = bis.read();
while (result != -1) {
buf.write((byte) result);
result = bis.read();
}
outputStream.write(buf.toByteArray());
System.out.println("File write success....");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code is running fine, but I'm seeing an error "Unexpected end of archive", and this zip file should contain three different files, but I see only one file and it has a size of zero.
I'm not sure what I'm doing wrong, anyone's help would be really appreciated.
Below is the working code for above requirement,
package com.pack.IOT;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test2 {
public static Connection con;
public static PreparedStatement stmt;
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url,uname,pwd);
stmt=con.prepareStatement("select * from FileStore");
ResultSet rs=stmt.executeQuery();
while (rs.next()) {
InputStream is = rs.getBinaryStream(3);
convert(is);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void convert(InputStream is) {
FileOutputStream outputStream = null;
File file = new File("C:\\Users\\nshaik\\Desktop\\IOTZip.zip");
try {
outputStream = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result;
result = bis.read();
while (result != -1) {
buf.write((byte) result);
result = bis.read();
}
outputStream.write(buf.toByteArray());
System.out.println("File write success....");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

PDF file corrupted after downloading from mysql java

I am trying to upload a pdf file to my database and trying to download same file but I am unable to open the file after it's downloaded I get an error stating file type not supported.
Here is the code for file Upload.
package itext;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
public class FileUpload {
public static void fileupload() throws FileNotFoundException{
String inFile="D:/Eclipse Java/myown.pdf";
FileInputStream io = new FileInputStream(inFile);
byte[] pdfData = new byte[(int) inFile.length()];
DataInputStream dis;
try {
dis = new DataInputStream(new FileInputStream(inFile));
dis.readFully(pdfData); // read from file into byte[] array
dis.close();
Connection dbConnection;
String myConnectionString =
"jdbc:mysql://******/*****";
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps = (PreparedStatement) dbConnection.prepareStatement("INSERT INTO Form_BL (AppID,Form) VALUES (?,?)");
ps.setString(1, "1");
ps.setBytes(2, pdfData); // byte[] array
ps.executeUpdate();
ps.setBinaryStream(1, (InputStream)dis,(int)inFile.length());
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the code for downloading
package itext;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.PreparedStatement;
public class FileDownload {
public static void filedownload(){
Connection dbConnection;
ResultSet rs;
String myConnectionString =
"jdbc:mysql://*****/*****";
try {
dbConnection = DriverManager.getConnection(myConnectionString, "****", "****");
PreparedStatement ps=(PreparedStatement) dbConnection.prepareStatement("select AppID from Form_BL where AppID='1' ");
rs=ps.executeQuery();
rs.next();
java.sql.Blob b=rs.getBlob(1);
byte barr[]=new byte[(int)b.length()];//an array is created but contains no data
barr=b.getBytes(1,(int)b.length());
FileOutputStream fout=new FileOutputStream("D:/download.pdf");
fout.write(barr);
fout.close();
System.out.println("ok");
dbConnection.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I was using the reference of the following link for this operation.
Upload PDF file to mysql BLOB by using java.sql.PreparedStatement without corruption. Thanks in advance
It looks like the code to save the binary content (PDF file) into a BLOB is fine. But when you try to get the PDF content back it looks like you have some trouble.
You might wan to try this:
Blob b = rs.getBlob(1);
InputStream is = b.getBinaryStream();
FileOutputStream fos = new FileOutputStream("D:/download.pdf");
int i = 0;
// IMPORTANT: Remember to handle/close all I/O properly
while ((i = is.read()) != -1) {
fos.write(b);
}

how to download file from file's path stored in MySql by using servlet,JSP

i want to download my file from file's path stored in Mysql by using JSP,actually i did it, but when download a file, it only has a file size= 0 KB, here is my code to download:
package rizki;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "downloadServlet2", urlPatterns = {"/downloadServlet2"})
public class downloadServlet2 extends HttpServlet {
static ResultSet result;
static Connection con;
static PreparedStatement stat;
static Statement st, st2;
private static String dataSourceName="odbcMySql";
private static String dbURL="jdbc:odbc:"+dataSourceName;
private static String dbUser="root";
private static String dbPass="085219236994";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("file_id");
String filePath="";
String fileName="";
String completeFile="";
String sql="select FileName,lokasi from savedFile where id= ?";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(dbURL,dbUser,dbPass);
stat=con.prepareStatement(sql);
stat.setString(1, id);
result=stat.executeQuery();
if (result.next())
{
fileName = result.getString(1);
filePath=result.getString(2);
}
completeFile=filePath+File.separator+fileName;
File downloadFile = new File(completeFile);
int length = 0;
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(completeFile);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
byte[] buffer = new byte[4096];
//int bytesRead = -1;
while ((in != null) && ((length = in.read(buffer)) != -1))
{
outStream.write(buffer,0,length);
}
in.close();
outStream.close();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
and this my code for storing file's path into database and copying file to C:\Users\KikiRizki\Documents\NetBeansProjects\BLH\build\web\folderFile
<%#page import="java.sql.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="java.util.*, java.io.*" %>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.List"%>
<%# page import="java.io.File"%>
<%# include file="koneksiDB.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
try
{
String files="";
String fileName="";
File savedFile=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Check that we have a file upload request
if(!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//ServletContext servletContext = this.getServletConfig().getServletContext();
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException Ex)
{
Ex.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if (name.equals("files"))
{
files=value;
}
}
else
{
try
{
fileName = item.getName();
savedFile = new File (config.getServletContext().getRealPath("/")+"\\folderFile\\"+fileName);
item.write(savedFile);
}
catch (Exception ex)
{
out.println("error "+ex.getMessage());
}
}
}
try
{
//CallableStatement cs = koneksi.prepareCall("{call insertVideo2 (?,?)}");
String st = "insert into savedFile(fileName,lokasi,uploader) values (?,?,?)";
PreparedStatement psmt=cn.prepareStatement(st);
psmt.setString(1,fileName);
psmt.setString(2,savedFile.getPath());
psmt.setString(3, "ADMIN BLH");
psmt.executeUpdate();
psmt.close();
cn.close();
out.println("upload success!");
out.println(" back to home");
//st.executeUpdate("insert into video values ('"+VideoName+"')");
///response.sendRedirect("AdminVideo.jsp");
}
catch (Exception ex)
{
out.println("Error "+ex.getMessage());
}
}
}
catch (Exception Ex)
{
out.println("error" +Ex.getMessage());
}
%>
</body>
Home Page
</html>
please help or correct if i'm wrong, i really appreciate your help, thank you very much
return the input stream which file will be downloaded from direct database
--
public static InputStream getTheDbFileInputStreamWhereId(String id) {
try {
String sql = "select songFile from songs where id= ?";
Connection con = getConnectionGp();
PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, id);
ResultSet result = stat.executeQuery();
if (result.next()) {
return result.getBinaryStream(1);
}
} catch (Exception e) {
System.out.println("prolbem in dao dwonload");
e.printStackTrace();
}
return null;
}
make the road clear to download the file in the doGet method
--
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
String fileName = Dao.getFileNameWhereId(id);
if (fileName == null) {
System.out.println("file name not found!");
return;
}
String resContentType = "APPLICATION/OCTET-STREAM";
response.setContentType(resContentType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
InputStream in = Dao.getTheDbFileInputStreamWhereId(id);
if (in == null) {
System.out.println("file not found according to id");
return;
}
for (int i = in.read(); i != -1; i = in.read()) {
out.write(i);
}
in.close();
out.close();
} catch (Exception e) {
System.out.println("problem occurs");
}
}
package rizki;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "downloadServlet2", urlPatterns = {"/downloadServlet2"})
public class downloadServlet2 extends HttpServlet {
static ResultSet result;
static Connection con;
static PreparedStatement stat;
static Statement st, st2;
private static String dataSourceName="odbcMySql";
private static String dbURL="jdbc:odbc:"+dataSourceName;
private static String dbUser="root";
private static String dbPass="085219236994";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("file_id");
String filePath="";
String fileName="";
String completeFile="";
String sql="select FileName,lokasi from savedFile where id= ?";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection(dbURL,dbUser,dbPass);
stat=con.prepareStatement(sql);
stat.setString(1, id);
result=stat.executeQuery();
if (result.next())
{
fileName = result.getString(1);
filePath=result.getString(2);
}
completeFile=filePath+File.separator+fileName;
File downloadFile = new File(completeFile);
if(downloadFile.exists()){
int length = 0;
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(completeFile);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
//OutputStream outStream = response.getOutputStream();
//DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
FileInputStream in = new FileInputStream(downloadFile);
byte[] buffer = new byte[4096];
//int bytesRead = -1;
int i;
while ((i=in.read()) != -1) {
out.write(i);
}
in.close();
out.close();
}else{
System.out.println("File does not exist at location "+downloadFile.getAbsolutePath());
}
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
You forgot to flush outStream.flush();
The code should be
while ((in != null) && ((length = in.read(buffer)) != -1))
{
outStream.write(buffer,0,length);
}
in.close();
outStream.flush();
outStream.close();
OutputStream outStream = response.getOutputStream(); change it to ServletOutputStream outStream = response.getOutputStream();
you can flush your outStream.flush();
change this ServletOutputStream outStream = response.getOutputStream(); to OutputStream outStream = response.getOutputStream();

How to upload file in database?

I am trying to upload an image file with the code below, but the file is not being uploaded. The console still shows the message "1 Record Successfully Inserted."
Create table image
(
name varchar2(20),
photo blob
);
import java.sql.*;
import java.io.*;
public class ImageWriter {
static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "SYSTEM", "SYSTEM");
PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");
FileInputStream fin = new FileInputStream("E:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin,fin.available());
int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");
connection.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
The above code works fine.
I dont know how you verified the contents of database.
Here is my code to verify the db(blob column): Try with this method. I used your code to insert the image and I could retrieve the image successfully. (note : file extension should be same)
public static void getPic() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "sys as sysdba",
"Oracle123");
ResultSet rs = null;
Statement stmt = null;
oracle.sql.BLOB photo = null;
conn.setAutoCommit(false);
stmt = conn.createStatement();
String name="ABC";
rs = stmt.executeQuery("select photo from image where name = '" + name + "'" );
rs.next();
photo = ((OracleResultSet) rs).getBLOB(1);
File f = new File("E:/image2.jpg");
f.getParentFile().mkdirs();
f.createNewFile();
InputStream in = photo.getBinaryStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream outputStream = new FileOutputStream(f);
int bufferSize = 1024;
int length = (int) photo.length();
byte[] buffer = new byte[bufferSize];
while((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
out.writeTo(outputStream);
System.out.println("Image Retrieved");
out.close();
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

How to use a string in a destination?

Hopefully a simple question :
I have created code to get a username from a log in page :
private String username;
#PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
but what I want to do is add the username to end of this destination :
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/";
how would I do it so it the destination would call the username to place the document in a file specific to that user ? this is all in the same bean
This is my currently bean
#ManagedBean(name = "fileUploadController")
public class FileUploadController {
private String username;
#PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(theFile + "/" + fileName)); // cannot find path when adding username atm
System.out.println(theFile); //testing
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
CURRENT EDIT :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.fileupload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
#ManagedBean(name = "fileUploadController")
public class FileUploadController {
private String username;
#PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public File getDirectory(String destination, String username) {
//set the user directory from the destinarion and the logged user name
File directory = new File(destination, username);
//check if the location exists
if (!directory.exists()) {
//let's try to create it
try {
directory.mkdir();
} catch (SecurityException secEx) {
//handle the exception
secEx.printStackTrace(System.out);
directory = null;
}
}
return directory;
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
System.out.println(directory); //testing
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
EDIT ::::
Now saying directory, in out = new FileOutputStream(new File(directory)); cannot find symbol also I get realFile not used
current code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.fileupload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
#ManagedBean(name = "fileUploadController")
public class FileUploadController {
private String username;
#PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution)
public File getDirectory(String destination, String username) { // currently not working, is not calling the username or directory
//set the user directory from the destinarion and the logged user name
File directory = new File(destination, username);
//check if the location exists
if (!directory.exists()) {
//let's try to create it
try {
directory.mkdir();
} catch (SecurityException secEx) {
//handle the exception
secEx.printStackTrace(System.out);
directory = null;
}
}
return directory;
}
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
//handle the exception
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
//get the directory assigned to the current user
File userDirectory = getDirectory(destination, username);
if (userDirectory != null) {
OutputStream out = null;
try {
File realFile = new File(userDirectory, fileName);
out = new FileOutputStream(new File(directory));
int read = 0;
//1024 must be a constant
//also, it must be 4098 (4 KBs) for better performance
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
out.close();
}
}
}
EDIT AGAIN LOL :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package richard.fileupload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
#ManagedBean(name = "fileUploadController")
public class FileUploadController {
private String username;
#PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads (will change this thanks to adivce )
File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution)
public File getDirectory(String destination, String username) {
// currently not working, is not calling the username or destination
//set the user directory from the destinarion and the logged user name
File directory = new File(destination, username);
//check if the location exists
if (!directory.exists()) {
//let's try to create it
try {
directory.mkdir();
} catch (SecurityException secEx) {
//handle the exception
secEx.printStackTrace(System.out);
directory = null;
}
}
return directory;
}
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
//handle the exception
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
//get the directory assigned to the current user
File userDirectory = getDirectory(destination, username);
if (userDirectory != null) {
OutputStream out;
try {
File realFile = new File(userDirectory, fileName);//realFile variable not used
out = new FileOutputStream(new File(userDirectory));// no suitable constructor found for File(File)
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
/**
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
System.out.println(directory); //testing
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
*/
This is my latest version of the code, I have tried to modify it, but it current throwing a few errors, I have added the errors in comments in the code, also is the public File getDirectory(String destination, String username) in the right place ? Thanks, I never would have thought I would have to do this much work to do something simple ! :D
Your problem is more related to File class usage than a JSF problem.
You can use this class to handle files or directories. To start with, you can have two methods:
a method that will retrieve the user directory
a method that will save the file in the user directory
Basic example:
//note: this must be moved to an utility class
public File getDirectory(String destination, String username) {
//set the user directory from the destinarion and the logged user name
File directory = new File(destination, username);
//check if the location exists
if (!directory.exists()) {
//let's try to create it
try {
directory.mkdir();
} catch (SecurityException secEx) {
//handle the exception
//this is a naive way to do it
secEx.printStackTrace(System.out);
directory = null;
}
}
return directory;
}
public void saveFile(String fileName, byte[] data) {
//get the directory assigned to the current user
File userDirectory = getDirectory(destination, username);
if (userDirectory != null) {
//create the real file using the directory as parent directory
//we'll give the file name too
//check the different constructors for File class
File realFile = new File(userDirectory, fileName);
//save the file the way you want/need...
//this should be also in an utility class
FileOutputStream fos;
try {
fos = new FileOutputStream(realFile);
fos.write(myByteArray);
} catch (Exception ex) {
//handle the exception
ex.printStackTrace(System.out);
} finally {
if (fos != null)
fos.close();
}
}
}
References:
byte[] to file in Java
FileOutputStream(File file) constructor
Based on your question edit, you must modify the copyFile in order to look as the saveFile method that I proposed. I'll change the implementation to use an InputStream.
public void copyFile(String fileName, InputStream in) {
//get the directory assigned to the current user
File userDirectory = getDirectory(destination, username);
if (userDirectory != null) {
OutputStream out;
try {
File realFile = new File(userDirectory, fileName);
out = new FileOutputStream(new File(userDirectory));
int read = 0;
//1024 must be a constant
//also, it must be 4098 (4 KBs) for better performance
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
out.close();
}
}
}

Categories

Resources