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;
- }
- }
- <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>
- <span style="white-space:pre"> </span></result>
- </action>
本文提供了一段使用Servlet和Struts2实现文件下载的简单代码示例,包括设置响应头、获取文件输入流并将其输出至客户端。

被折叠的 条评论
为什么被折叠?



