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配置文件
jsp页面
location.href="downloadFile.do";
参考链接: