Struts2文件下载

来源:互联网 发布:业务流程数据化的例子 编辑:程序博客网 时间:2024/06/16 07:20

方法1、在struts中使用servlet下载

public class DownLoadAction extends ActionSupport {public String download() throws IOException{HttpServletResponse response = ServletActionContext.getResponse();String path = ServletActionContext.getRequest().getRealPath("/Download/旅行.jpg");//获得资源绝对路径String filename = path.substring(path.lastIndexOf("\\")+1);//获得文件名        filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码//response.setHeader("content-disposition", "attachment;filename="+filename);//如果资源名称是中文,则应该用URLEncoder转码,设置响应头为文件下载response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));InputStream in = null;OutputStream out = null;try{in = new FileInputStream(path);//读文件int len = 0;byte []buf = new byte[1024];out = response.getOutputStream();while((len = in.read(buf)) > 0){out.write(buf,0,len);//写入response对象}}finally{//关闭流if(in != null){try{in.close();}catch(Exception e){}}if(out != null){try{out.close();}catch(Exception e){}}}return null;    //一定要返回null,所以在<action></action>中不用配置result}}


2、使用Response下载

DownLoadResponseAction.java

public class DownLoadResponseAction extends ActionSupport {//filename = new String(filename.getBytes("iso8859-1"),"UTF-8");private String filename;@Overridepublic String execute() throws Exception {filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");//改编码System.out.println(filename);HttpServletRequest request = ServletActionContext.getRequest();//获得requestHttpServletResponse response = ServletActionContext.getResponse();//获得responseString path = request.getRealPath("/DownLoad");//得到资源的路径File file = new File(path+filename);response.setCharacterEncoding("UTF-8");        filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码response.setHeader("content-disposition", "attachment;filename="+filename);//设置响应头为文件下载response.setContentLength((int)file.length());int len = 0;byte []buffer = new byte[1024];InputStream is = new FileInputStream(file);OutputStream os= response.getOutputStream();//向浏览器写数据while((len = is.read(buffer)) != -1){os.write(buffer,0,len);}is.close();os.close();return null;}public String getFilename() {return filename;}public void setFilename(String filename) {this.filename = filename;}}





0 0
原创粉丝点击