Java Servlet下载文件(简单)


package com.bjdata.bjproduct.presentation.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bjdata.bjproduct.common.Constants;
import com.bjdata.bjproduct.persistence.system.model.User;
import com.sun.xml.internal.fastinfoset.stax.events.Util;


public class FileDownload extends HttpServlet {

	private int bufferSize=2048;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String bsize=config.getInitParameter("bufferSize");
		if(Util.isEmptyString(bsize)){
			bufferSize=Integer.parseInt(bsize);
		}
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action="";
		try{
			
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			
			String id=request.getParameter("id");
			String company=request.getParameter("company");
			action="/infoManager/getContract.do?id="+id+"&company="+company;
			//文件名必须带后缀名,否则 下载后是未知类型的文件
			String filename=request.getParameter("filename");
			String path = request.getParameter("path");
			
			path=request.getSession().getServletContext().getRealPath("/")+path;
			
			User sessionuser = (User) request.getSession(true).getAttribute(
					Constants.SESSION_USER);
			if(sessionuser!=null){
				//检测文件是否存在
				File file=new File(path);
				
				if(!file.exists()){
					request.setAttribute("msg","");
					request.getRequestDispatcher(action).forward(request, response);
				}else{
					response.reset();
					//将 文件流写入到前端浏览器
					response.setHeader("Content-disposition", "attachment;filename="+convertFileName(filename));
					ServletOutputStream sops=response.getOutputStream();
					FileInputStream fis=new FileInputStream(file);
					copyStream(fis,sops,true);
					fis.close();
					sops.close();
					fis=null;
					sops=null;
					file=null;
				}
				
			}
			else{
				//response.sendRedirect("index.jsp");(如果是重定向:index.jsp 中需要通过js控制跳到top.location.href="login.jsp")
//下面实现了 top.location.href="login.jsp" 的效果
				response.getWriter().print("");
			}
		}catch(Exception e){
			request.setAttribute("msg", "");
			request.getRequestDispatcher(action).forward(request, response);
			e.printStackTrace();
		}
	}
	/**
	 * 复制流 到 前端浏览器
	 * @param source 源文件输入流
	 * @param dest 输出流
	 * @param flush 
	 * @return
	 */
	private final long copyStream(InputStream source,OutputStream dest,boolean flush){
		int bytes;
		long total=0l;
		byte [] buffer=new byte[bufferSize];
		try {
			while((bytes=source.read(buffer))!=-1){
				if(bytes==0){
					bytes=source.read();
					if(bytes<0)
						break;
					dest.write(bytes);
					if(flush)
					   dest.flush();
					total+=bytes;
				}
				dest.write(buffer,0,bytes);
				if(flush)
					dest.flush();
				total+=bytes;
			}
			
		} catch (IOException e) {
			throw  new RuntimeException("IOException caught while copying.",e);
		}
		return total;
	}
	
	//转换文件名的方法 在strust.xml中会用到  
    public String convertFileName(String cfilename){  
        try {  
        	cfilename=new String(cfilename.getBytes(),"ISO-8859-1");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return cfilename;  
    } 
    
    
}

web.xml
 
  
    FileDownload
    com.bjdata.bjproduct.presentation.servlet.FileDownload
    
    	bufferSize
    	2048
    
  


    FileDownload
    /download
  

你可能感兴趣的:(Java Servlet下载文件(简单))