File get currupt if downloaded by response.getOutputStream();

Joined
Apr 10, 2010
Messages
1
Reaction score
0
Hi,
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,189
Members
46,735
Latest member
HikmatRamazanov

Latest Threads

Top