您的位置:首页 > 编程语言 > Java开发

Struts2和Servlet下载文件的区别

2013-03-22 15:53 351 查看
不得不说使用了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方式下载

误区:导致页面跳转....,理解不深。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: