Struts2和Servlet下载文件的区别
2013-03-22 15:53
351 查看
不得不说使用了struts2,在下载文件时变得非常方便,不需要像servlet那样一个读流,一个写流,虽然就几行代码。但相比struts2还是弱爆了。
不过话说回来,框架倒是给你省了不少事,但掌握servlet的下载方式还是非常重要的,毕竟是根本的东西。
总结:相比之前,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在上传文件时的区别
- PrintWriter与ServletOutputStream的区别之文件下载
- 工作记录:文章详情页的附件下载,基于struts2的文件下载
- Struts2系统学习(10)文件上传与下载案例及原理分析
- 文件下载 上传ext4.0.7+struts2
- struts2文件下载
- [转]JSP或servlet中(以及上传下载文件)中文乱码或不显示的解决方案
- Struts2文件的上传和下载实现
- struts2实现文件上传和下载
- n文件的上传和下载,struts2和springmvc
- struts2文件下载showModalDialog()中不弹出对话框
- jsp+servlet实现文件的上传和下载
- struts2 文件上传与下载原理
- 周报8.15-8.21 struts2实现文件上传和下载(下载)
- 基于servlet的文件下载
- struts2的文件下载
- Java EE开发第十二章:1.Servlet之Response相应(重定向、操作相应体、文件下载、随机验证码)
- Struts2文件上传与下载
- Jsp+Servlet实现文件上传下载 删除上传文件(三)