why my download file always got corrupted.
I have a code that will upload file using blob.
the code is
InputStream inputStream = new FileInputStream(new File(filePath)); //the file to upload
pst.setBinaryStream(15, inputStream); //to upload the selected file
it's successfully upload to my sql data base but when I try to download it, it always got corrupted.
below is my code to download the file from sql.
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url1 = "jdbc:sqlserver://ets88-spare:1433;databaseName=users;user=sa;password=test";
Connection conn1 = DriverManager.getConnection(url1);
String query1 = "SELECT * FROM ets_verification";
Statement state = conn1.createStatement();
ResultSet rs = state.executeQuery(query1);
while (rs.next())
{
String boardname = jboardName.getSelectedItem().toString();
String sn = jserialNumber.getText();
String status = jverificationStatus.getSelectedItem().toString();
String filename = boardname + "_" + "_" + sn + "_"+ status;
byte[] array = rs.getBytes(16);
FileOutputStream fos = new FileOutputStream("c:\\" + filename + ".rar");
fos.write(array);
fos.close();
System.out.println("array:" + array);
}
}
catch (ClassNotFoundException | SQLException e)
{
jnote.setText(e.toString());
System.out.println("error" + e.toString());
} catch (IOException ex) {
Logger.getLogger(ets_verification.class.getName()).log(Level.SEVERE, null, ex);
}
You could try.
Tested in a ORACLE DB.
(...)
Blob blob = rs.getBlob(16);
if (blob != null) {
byte[] b = blob.getBytes(1, (int) blob.length());
try (FileOutputStream fos = new FileOutputStream("PATH/TO/FILE/FILENAME.rar")){
fos.write(file);
}catch (IOException ex) {
//Do something
}
}
(...)
Related
ok, the below statement works with there wasnt a row create. and in my code i push a file into my database with binary stream and in the code below you see this, and it works but i need it to update a row instead of insert, how would i do that?
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
File f = fc.getSelectedFile();
File j = f;
//String path = f.getAbsolutePath();
//picPreview.setIcon(new ImageIcon(path));
try{
BufferedImage image = ImageIO.read(j);
BufferedImage scaled = getScaledInstance(
image, picPreview.getWidth(), picPreview.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
picPreview.setIcon(new ImageIcon(scaled));
}catch(Exception ex){
}
try{
FileInputStream fin = new FileInputStream(f);
int len = (int)f.length();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
PreparedStatement ps = con.prepareStatement("INSERT INTO listings(itemPicture) VALUES(?)");
ps.setBinaryStream(1, fin, len);
int status = ps.executeUpdate();
if(status>0){
jLabel2.setText("Successfully uploaded image to database");
}
else{
jLabel2.setText("Upload Failed!");
}
}catch(Exception e )
{
JOptionPane.showMessageDialog(null,e, "Error ", JOptionPane.ERROR_MESSAGE);
}
i tried to put VALUES(?) and i used a variable i had but i failed miserably
"UPDATE listings SET itemPicture=VALUES(?) WHERE itemVin='" + VinNum + "'");
I cant understand why my code are not running all the time.
I am opening a jasper report but for first 4 opening times the report is cached or code are not executing (Code in the new StreamResource are not executing first 4 times). new StreamResource.StreamSource() are running only at 5 time WHY ? The first 4 times i got the old,cached,temp or i event dont know what a pdf file with old params.
maybe someone know the issue ?
public static void open(final String fileName, final HashMap<String, Object> data ) {
mylog.pl("### Param's print # open Report: Filename:" + fileName);
try {
Iterator<?> i = data.keySet().iterator();
while (i.hasNext()) {
String id = i.next().toString();
String value = (data.get(id) != null) ? data.get(id).toString() : "null";
mylog.pl(" id: " + id + " value: " + value);
}
} catch (Exception e) {
e.printStackTrace();
mylog.pl(e.getMessage());
}
StreamResource.StreamSource source = null;
source = new StreamResource.StreamSource() {
public InputStream getStream() {
byte[] b = null;
InputStream reportStream = null;
try {
reportStream = new BufferedInputStream(new FileInputStream(PATH + fileName + JASPER));
b = JasperRunManager.runReportToPdf(reportStream, data, new JREmptyDataSource());
} catch (JRException ex) {
ex.printStackTrace();
mylog.pl("Err # JR" + ex.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
Utils.showMessage(SU.NOTFOUND);
return null;
}
return new ByteArrayInputStream(b);
}
};
StreamResource resource = null;
resource = new StreamResource(source, fileName + PDF);
resource.setMIMEType("application/pdf");
Page p = Page.getCurrent();
p.open(resource, "Report", false);
}
Here is the answer
I all the time used resource.setCacheTime(0); but really needed resource.setCacheTime(1000); because
In theory <= 0 disables caching. In practice Chrome, Safari (and,
apparently, IE) all ignore <=0.
I'm trying to store a text file in a MySQL database, and when needed, save it to a file.
To save the file, I do:
public void saveFile_InDB(File file)
{
try {
String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, new Date().toString());
statement.setString(2, new Date().toString());
InputStream inputStream = new FileInputStream(file);
statement.setBinaryStream(3, inputStream);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("File saved sucessfully.");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
And to retreive and save the file:
public void retrieveFile_fromDB()
{
try {
Statement stmt = (Statement) conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
FileOutputStream fos = new FileOutputStream("file.txt");
if (res.next()) {
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
}
} catch (IOException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
} catch (SQLException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
}
Storing the file works, but when I try to retrieve and save it, nothing is stored in the output file?
if you want read file from db Mysql
change this part in your code
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
use this code read array of bytes
byte [] bs=res.getBytes("fileName");
fos.write(bs);
it will work
if you return multiple files from db you must declare
FileOutputStream fos = new FileOutputStream("file.txt");
inside while loop and change name of file to avoid overriding
You do not seem to put into the database the things that the column names describe?
fileName and time are for example both set to a timestamp, and clientName is set to the contents of the file. When you later try to select based on clientName, you are actually selecting based on the contents of the file.
Furthermore, when reading the data, you are reading the blob data from the column fileName, but this is wrong because:
fileName contains new Date().toString(), not the contents of the file
fileName should surely contain the file's name, not its contents?
Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);
I'm trying to find a way to save a video file. Initially I'd put the video files as blob data into a database, and now, I'm trying to get the blob data back, convert it into bytes, and then write it to a new file. I've been successful in doing this, but the problem is, I can't make the resulting files to run. I tried storing, retrieving, and writing .flv and .mp4 files, but neither work :/ Can anyone help me? Much appreciated! :)
Here is my code: :)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root","password");
Statement st1 = (Statement) con.createStatement();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = con.prepareStatement("SELECT video_file from video where video_id = " + video_id);
rs = pstmt.executeQuery();
Blob blob = null;
byte[] blyte = null;
if(rs.next()) {
blob = rs.getBlob("video_file");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("C:\\Downloads\\file2.mp4");
int b = 0;
while(b != -1){
fos.write(b);
b = bis.read();
}
}
//exceptions beyond this point
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
There is a '\0' byte written to fos in first iteration of the while-loop which does not come from bis.read().