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
- struts2实现文件下载
- struts2文件下载
- Struts2控制文件下载
- struts2文件下载
- Struts2 文件下载
- ext + struts2 下载文件
- Struts2文件下载
- Struts2文件下载
- struts2文件下载
- Struts2文件下载
- Struts2 的文件下载
- Struts2 的文件下载
- Struts2文件的下载
- Struts2文件下载
- struts2.1文件下载
- struts2文件下载
- struts2下载文件
- struts2 文件下载
- ffmpeg裁剪合并视频
- Html手记:表单标签
- R判断逻辑回归参数共线性
- 【51 Nod1378】夹克老爷的愤怒
- JavaEE Spring框架学习笔记(理论学习之通过@Autowired 自动装配注解的使用)
- Struts2文件下载
- 【51nod1403】 有趣的堆栈
- R语言画图-Error in get(getOption("device"))
- leetcode : Add Two Numbers
- 文章标题
- 数值分解
- 项目实战篇-餐馆管理系统—MFC,PHP,MySql:3.MFC端Person类及个人信息修改
- Android自定义简易照相机
- JS 10进制转其他进制