Hi,
I am trying to download file (of any type pdf/rar/any etc...) using following code,
but SOME TIME downloaded file is currupted.
but when I use
insted of
It works, & download file by name "MyFile" in bin of tomcat folder.
but not work with response object.
I am trying to download file (of any type pdf/rar/any etc...) using following code,
but SOME TIME downloaded file is currupted.
Code:
public static boolean downloadAttachment(HttpServletResponse response,
String filePath, String attachmentName) throws Exception {
boolean fileDownloadedStatus = false;
FileInputStream fileInputStream = null;
OutputStream outputStream = null;
FileChannel source = null;
FileChannel destination = null;
try {
File file = new File(filePath);
if (file.exists()) {
if(isDebugEnabled)
log.debug("File Found");
}
String quotes = "\"";
attachmentName = quotes.concat(attachmentName).concat(quotes);
response.setContentType("application/unknown");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=0");
response.addHeader("Content-Disposition", "attachment; filename="
+ attachmentName);
fileInputStream = new FileInputStream(file);
OutputStream tempStream = response.getOutputStream();
if (tempStream instanceof FileOutputStream && tempStream != null) {
destination = ((FileOutputStream) tempStream).getChannel();
source = new FileInputStream(file).getChannel();
destination.transferFrom(source, 0, source.size());
} else {
outputStream = tempStream;
int bytesRead;
while ((bytesRead = fileInputStream.read()) != -1){
outputStream.write(bytesRead);
}
}
fileDownloadedStatus = true;
} catch (FileNotFoundException fileNotFoundException) {
log.error("FileNotFoundException");
throw fileNotFoundException;
} catch (Exception exception) {
log.error("Exception");
throw exception;
} finally {
if (source != null)
source.close();
if (destination != null)
destination.close();
if (fileInputStream != null)
fileInputStream.close();
if (outputStream != null)
outputStream.close();
}
return fileDownloadedStatus;
but when I use
Code:
File f1=new File("MyFile");
OutputStream outputStream=new FileOutputStream(f1);
insted of
Code:
OutputStream tempStream = response.getOutputStream();
It works, & download file by name "MyFile" in bin of tomcat folder.
but not work with response object.