1 package org.jahia.tools.files; 2 3 4 9 10 11 import java.io.*; 12 import java.util.*; 13 import javax.servlet.*; 14 import javax.servlet.http.*; 15 16 import com.oreilly.servlet.*; 17 18 25 public class FileDownload { 26 27 28 private HttpServletRequest m_Req; 29 private HttpServletResponse m_Res; 30 31 private String m_FileRealName = ""; 32 private String m_FileStorageFullPath = ""; 33 private String m_FileContentType = ""; 34 35 private int m_BufferSize = 4096; 36 private byte[] m_WriteBuffer = new byte[m_BufferSize]; 37 38 39 48 public FileDownload( 49 HttpServletRequest req, 50 HttpServletResponse res, 51 String fileRealName, 52 String fileStorageFullPath, 53 String fileContentType){ 54 55 m_Req = req; 56 m_Res = res; 57 m_FileRealName = fileRealName; 58 m_FileStorageFullPath = fileStorageFullPath; 59 m_FileContentType = fileContentType; 60 61 } 62 63 64 70 public void writeFileContentToResponse() throws IOException { 71 72 toConsole("FileDownload, fullRealpath is " + m_FileStorageFullPath); 73 File theFile = new File(m_FileStorageFullPath); 74 if ( theFile.exists() && theFile.isFile() && theFile.canRead() ){ 75 76 m_Res.setContentLength((int)theFile.length()); 78 m_Res.setContentType(m_FileContentType); 79 m_Res.setHeader("Content-Disposition","attachment; filename=\"" + m_FileRealName + "\""); 80 m_Res.setDateHeader("Date", new Date().getTime()); 81 m_Res.setDateHeader("Expires", new Date().getTime()); 82 m_Res.setIntHeader("Age",0); 83 m_Res.setIntHeader("Retry-After",60); 84 m_Res.setHeader("Pragma","no-cache"); 85 m_Res.setHeader("Connection","Keep-Alive"); 86 87 try { 88 copyStream(new FileInputStream(m_FileStorageFullPath), m_Res.getOutputStream()); 89 } catch (IOException ioe) { 90 toConsole("FileDownload :: Error writing file to response" + ioe.getMessage()); 91 throw new IOException("FileDownload::writeFileContentToResponse error while writing to client"); 92 } 93 } else { 94 toConsole("FileDownload :: checkFile, file denoted by " + m_FileStorageFullPath + " doesn't exist or cannot be read"); 95 throw new IOException("FileDownload::writeFileContentToResponse error while trying to open file"); 96 } 97 98 } 99 100 101 108 private void copyStream(InputStream ins, 109 OutputStream outs) 110 throws IOException 111 { 112 BufferedInputStream bis = 113 new BufferedInputStream(ins, m_BufferSize); 114 BufferedOutputStream bos = 115 new BufferedOutputStream(outs, m_BufferSize); 116 int bufread; 117 while((bufread = bis.read(m_WriteBuffer)) != -1) 118 bos.write(m_WriteBuffer,0,bufread); 119 bos.flush(); bos.close(); 120 bis.close(); 121 } 122 123 124 125 130 public void toConsole(String msg) { 131 System.out.println(msg); 132 } 133 134 } 135 136 | Popular Tags |