servlet实现下载

package org.imos.manager.action;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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

public class BaseServlet extends HttpServlet {

	
	@Override
	/**
	 * 进行消息转发
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//get method name
		String action = request.getParameter("action");
		Class clazz = this.getClass();
		Class[] types = {HttpServletRequest.class,HttpServletResponse.class};
		try {
			Method method = clazz.getDeclaredMethod(action, types);
			method.setAccessible(true);
			Object objs [] = {request,response};
			method.invoke(this, objs);
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			throw (RuntimeException)e.getTargetException();
		}
	}
}


public class FileUploadAndDownload extends BaseServlet {
public void fileDownload(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
    	 String filepath = request.getParameter("filepath");  
    	 // web绝对路径  
    	 String path = request.getSession().getServletContext().getRealPath("/");  
    	 // 设置为下载application/x-download  
    	 response.setContentType("application/x-download");  
    	 // 即将下载的文件在服务器上的绝对路径  
    	 String filenamedownload = path + "/" + filepath;  
    	 // 下载文件时显示的文件保存名称 
    	 String filenamedisplay = filepath.substring(filepath.lastIndexOf("/")+1) ;  
    	 // 中文编码转换  
    	 filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");  
    	 response.addHeader("Content-Disposition", "attachment;filename="+ filenamedisplay); 
    	 try {  
    		 java.io.OutputStream os = response.getOutputStream();   
    		 java.io.FileInputStream fis = new java.io.FileInputStream(filenamedownload);  
    		 byte[] b = new byte[1024];   
    		 int i = 0;   
    		 while ((i = fis.read(b)) > 0) {    
    			 os.write(b, 0, i);  
    		 }   
    		 fis.close();  
    		 os.flush();   
    		 os.close();  
    		} catch (Exception e) { 
    			
    		}
    	
    }
}


   

你可能感兴趣的:(servlet实现下载)