Struts2和Servlet下载文件的区别
来源:互联网 发布:如何将linux移植到arm 编辑:程序博客网 时间:2024/06/06 05:12
不得不说使用了struts2,在下载文件时变得非常方便,不需要像servlet那样一个读流,一个写流,虽然就几行代码。但相比struts2还是弱爆了。
不过话说回来,框架倒是给你省了不少事,但掌握servlet的下载方式还是非常重要的,毕竟是根本的东西。
1.Servlet下载简单代码
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Cache-Control", "no-cache"); resp.setContentType("application/vnd.ms-excel"); resp.setHeader("Content-Disposition", "attachment; filename=file.xls"); OutputStream os = resp.getOutputStream(); FileInputStream in = new FileInputStream(new File("xxxxx")); int n = 0;// 每次读取的字节长度 byte[] bb = new byte[1024];// 存储每次读取的内容 while ((n = in.read(bb)) != -1) { os.write(bb, 0, n);// 将读取的内容,写入到输出流当中 } os.close();// 关闭输入输出流 in.close(); }
2.Stuts2下载简单代码
public class TestAction { private InputStream excelStream; private String filename; /** * 物理存在的excel文件 * @return * @throws UnsupportedEncodingException */ public String down() throws UnsupportedEncodingException{ File file = new File( "xxxx");//文件路径 try { excelStream=new FileInputStream(file); filename=new String("真实excel文件".getBytes("UTF-8"),"ISO8859-1"); } catch (FileNotFoundException e) { e.printStackTrace(); } return "success"; } /** * @return the excelStream */ public InputStream getExcelStream() { return excelStream; } /** * @param excelStream the excelStream to set */ public void setExcelStream(InputStream excelStream) { this.excelStream = excelStream; } /** * @return the filename */ public String getFilename() { return filename; } /** * @param filename the filename to set */ public void setFilename(String filename) { this.filename = filename; } }struts.xml配置文件:
<action name="down" class="com.techbirds.action.TestAction" method="down"> <result name="success" type="stream"> <param name="contentType">application/vnd.ms-excel </param> <param name="inputName">excelStream</param> <param name="contentDisposition">filename="${filename}.xls" </param> <param name="bufferSize">1024</param> </result> </action>
总结:相比之前,struts2明显比较简单,除了一堆配置(固定的),还是简单总结下,servlet需要流之间的转换而struts2直接获取输入流便可。
3.ajax无法下载文件,替换window.location.href方式下载
误区:导致页面跳转....,理解不深。。
- Struts2和Servlet下载文件的区别
- Struts2和Servlet下载文件的区别
- Struts2和Servlet在上传文件时的区别
- servlet和struts2的区别和联系
- struts2和servlet区别
- struts2和servlet区别
- struts2和servlet区别
- struts2和servlet区别
- struts2和servlet区别
- struts2和servlet区别
- Struts2的学习及Struts2和Servlet的区别
- servlet进行文件的上传和下载
- servlet实现文件的上传和下载
- 关于文件上传和下载的Servlet
- Struts2文件的上传和下载
- Struts2文件的上传和下载
- struts2文件的上传和下载功能
- Struts2文件的上传和下载
- cassandra的数据类型
- springmvc+activiti 完美整合- 流程在线设计+代码生成器+UI快速开发库,提高一半的开发效率
- 分布式系统原理要点
- Ruby 1.9 - invalid multibyte char (US-ASCII)
- ASIHttpRequest "_UTTypeCopyPreferredTagWithClass", referenced from:
- Struts2和Servlet下载文件的区别
- linq学习链接
- 要毕业了,不是程序员,不是研究僧,是个雕栏外的小书童
- Python中的easy_install
- RCP-其他类型对话框
- 让所有浏览器支持max-height、min-height CSS样式
- 第三次作业
- WINCE API集合
- 网络数据传输时的疑惑点记录