jsp实现Servlet文件下载的方法
本文实例讲述了jsp实现Servlet文件下载的方法。分享给大家供大家参考。具体如下:
packagecom;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.net.URLEncoder;
importjava.util.Date;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importcom.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
/**
*文件下载类。为了防止客户端浏览器直接打开目标文件(例如在装了MSOffice套件的Windows中的IE浏览器可能就会直接在IE浏览器中打开你想下载的doc或者xls文件),在响应头里加入强制下载的MIME类型。
*/
publicclassDownloadFileextendsHttpServlet{
privatestaticfinalLoglog=LogFactory.getLog(DownloadFile.class);
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException{
longtimeStart=0;
if(log.isDebugEnabled()){
timeStart=System.currentTimeMillis();
}
response.setContentType("application/x-downloadcharset=UTF-8");
java.io.FileInputStreamfis=null;
Stringfilepath=request.getRealPath("");
javax.servlet.ServletOutputStreamsos=null;
//System.out.println("DownloadFilefilename:"+filename);
try{
if(request.getParameter("filename")==null
||request.getParameter("showName")==null){
return;
}
Stringfilename=request.getParameter("filename");
StringshowName=request.getParameter("showName");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
java.io.Filefile=newjava.io.File(filepath+filename);
if(!file.exists()){
log.error(file.getAbsolutePath()+"文件不存在!");
return;
}
//读取文件流
fis=newjava.io.FileInputStream(file);
//设置下载保存的文件名
sos=response.getOutputStream();
showName+=filename.substring(filename.lastIndexOf("."));
StringcontentDisposition="",browser=getBrowser(request);
if("IE".equals(browser)){
contentDisposition="attachment;filename="+URLEncoder.encode(showName,"UTF-8").replace("+","%20");
}elseif("CH".equals(browser)){
contentDisposition="attachment;filename="+MimeUtility.encodeText(showName,"UTF8","B");
}elseif("SF".equals(browser)){
contentDisposition="attachment;filename="+newString(showName.getBytes("UTF-8"),"ISO8859-1");
}else{
contentDisposition="attachment;filename*=UTF-8''"+URLEncoder.encode(showName,"UTF-8").replace("+","%20");
}
response.setHeader("Content-Disposition",contentDisposition);
intbyteCount=0;
if(fis!=null){
byte[]buff=newbyte[1024];
intbytesRead;
while(-1!=(bytesRead=fis.read(buff,0,buff.length))){
sos.write(buff,0,bytesRead);
sos.flush();
byteCount+=bytesRead;
}
}
sos.flush();
if(log.isDebugEnabled()){
log.debug("文件下载完成,文件大小:"+byteCount+",总共用时:"+(newDate().getTime()-timeStart)+"毫秒。");
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}finally{
try{
if(fis!=null){
fis.close();
}
}catch(IOExceptione){
}finally{
try{
if(sos!=null){
sos.close();
}
}catch(IOExceptione){
}
}
}
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
response.setContentType("text/html");
PrintWriterout=response.getWriter();
out.println("<!DOCTYPEhtmlPUBLIC\"-//W3C//DTDXHTML1.0Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
out.println("<html>");
out.println("<head>");
out.println("<title>文件下载</title>");
out.println("<metahttp-equiv=\"Content-Type\"content=\"text/html;charset=UTF-8\"/>");
out.println("</head>");
out.println("<body>");
out.print("Thisis");
out.print(this.getClass().getName());
out.println(",usingthePOSTmethod");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
privateStringgetBrowser(HttpServletRequestrequest){
StringuserAgent=request.getHeader("USER-AGENT").toLowerCase();
if(userAgent!=null){
if(userAgent.indexOf("msie")>=0){
return"IE";
}elseif(userAgent.indexOf("mozilla")>=0){
return"FF";
}elseif(userAgent.indexOf("applewebkit")>=0){
return"CH";
}elseif(userAgent.indexOf("safari")>=0){
return"SF";
}elseif(userAgent.indexOf("opera")>=0){
return"OP";
}
}
returnnull;
}
}
希望本文所述对大家的JSP程序设计有所帮助。