struts1.x下载文件

Action类

package com.cmsz.rist.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;


public class DownloadFile extends DispatchAction{
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)  {
        
        String path = request.getSession().getServletContext().getRealPath("/")+"excelTemplate/keywordTemplate.xls";
        BufferedInputStream   bis = null;
        BufferedOutputStream  bos = null;
        InputStream fis = null;
        OutputStream fos = null;
        
        try{

            File uploadFile = new File(path);

    
            fis = new FileInputStream(uploadFile);
            bis = new BufferedInputStream(fis);
            fos = response.getOutputStream();
            bos = new BufferedOutputStream(fos);
            


            response.reset();
            response.setHeader("Content-disposition", "attachment;filename =" + URLEncoder.encode(path.substring(path.lastIndexOf("/")+1), "utf-8"));


            int bytesRead = 0;
            byte[] buffer = new byte[4096];
            while((bytesRead = bis.read(buffer,0,4096)) != -1){
                bos.write(buffer, 0, bytesRead);
            }
            bos.flush();
            fis.close();
            bis.close();
            fos.close();
            bos.close();
            //return mapping.findForward("success");
            
            return null;
        }catch(FileNotFoundException e){
            e.printStackTrace();        
            return mapping.findForward("error");
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
        
    }

}
struts1.x配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
	
	<action-mappings>
		
		<action path="/downloadFile" type="com.mcbeath.file.DownloadFile" parameter="method" scope="request">
		</action>
	</action-mappings>	
	
</struts-config>
jsp页面

location.href="downloadFile.do";

参考链接:http://fighter1945.iteye.com/blog/316377


你可能感兴趣的:(struts1.x下载文件)