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方式下载

误区:导致页面跳转....,理解不深。。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值