file download not working
jsfgeeks Jan 25, 2010 2:30 AMhello,
In my project i am usiong button to download a file but it's not working properly other than save dialog it's shows file on the browser.My download code is below:
in first i tried servlet output stream & in second i tried to use BufferedOutputStream.but both are not working for me.
public String btn_download1_action() {
try {
if (news_filepath != null) {
String path =sc.getRealPath(ex_file_path)+"/"+news_filepath;
System.out.println(path);
String extension = path.substring(path.lastIndexOf(".") + 1);
System.out.println(extension);
File file = new File(path);
BufferedInputStream input = null;
long length = file.length();
ServletOutputStream output = null;
try {
// Open file.
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
// Init servlet response.
response.reset();
response.setContentType("application/force-download");
response.setContentLength(input.available());
response.addHeader("Content-disposition", "attachment; filename=\"" + news_filepath + "\"");
// output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// // Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
// for (int length; (length = input.read(buffer)) != -1;) {
// output.write(buffer, 0, length);
// }
// Finalize task.
output = response.getOutputStream();
response.setContentLength((int)length);
while ((input != null) && ((length = input.read(buffer)) != -1)) {
output.write(buffer, 0, (int)length);
}
output.flush();
} finally {
// Gently close streams.
input.close();
output.close();
}
}
} catch (Exception e) {
System.out.println(e);
}
// FacesContext.getCurrentInstance().responseComplete();
return null;
}
public String btn_download2_action() {
try {
if (news_picpath!= null) {
String path1 =sc.getRealPath(ex_file_path)+"/" +news_picpath;
System.out.println(path1);
String extension1 = path1.substring(path1.lastIndexOf(".") + 1);
System.out.println(extension1);
File file = new File(path1);
BufferedInputStream input1 = null;
BufferedOutputStream output1 = null;
try {
// Open file.
input1 = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
// Init servlet response.
response.reset();
response.setContentType("application/" + extension1 + "");
response.setContentLength(input1.available());
response.setHeader("Content-disposition", "attachment; filename=\"" + path1 + "\"");
output1 = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer1 = new byte[DEFAULT_BUFFER_SIZE];
for (int length1; (length1 = input1.read(buffer1)) != -1;) {
output1.write(buffer1, 0, length1);
}
// Finalize task.
output1.flush();
} finally {
// Gently close streams.
input1.close();
output1.close();
}
}
} catch (Exception e) {
System.out.println(e);
}
// FacesContext.getCurrentInstance().responseComplete();
return null;
}
any help would greatly appreciated.