ITeye博客

关于在Struts中文件下载功能实现的关键代码

zz130jj · 2010-07-14 13:58 · 编程语言 · Java · Apache · Myeclipse · Struts · JSP · Markdown

与文件上传相比,Struts中的文件下载相对要简单的多。今天只做一个简单的例子,在这个例子上稍加修改便可做到灵活应用。 首先要做的仍然是新建一个web工程,如果是MyEclipse 则导入Struts支持,Eclips则导入Struts相应jar包 下面进入正题,文件下载的关键代码如下: Action中的文件下载代码 package com.action; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; public class DownloadAction extends DispatchAction { public ActionForward down(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { //设置字符编码格式 response.setCharacterEncoding("utf-8"); try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //从页面得到传入的要下载文件的名称 String filename = request.getParameter("filename"); try { //将文件名从utf-8转化为iso-8859-1 filename = new String(filename.getBytes("iso-8859-1"), "utf-8"); //得到要下载文件的具体路径 String path = request.getRealPath("vadio") + "\\" + filename; //实例化出要下载文件 File file = new File(path); //得到要下载文件的文件读取流 InputStream is = new FileInputStream(file); //定义文件输入流,用于下载文件 OutputStream os = response.getOutputStream(); //设置响应体属性,文件下载操作的关键就在这儿 response.addHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("iso-8859-1"),"utf-8")); //文件头属性设置 response.addHeader("Content-length", file.length() + ""); //响应体内容设置 response.setContentType("application/octet-stream"); //下载文件大小记数器 int count = 0; //实例化一个byte数组用于写入一次写入文件的大小 byte[] buffer = new byte[1024 * 1024]; //如果读取文件成功 while ((count = is.read(buffer)) != -1) { //下载文件 os.write(buffer, 0, count); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } Struts配置文件: web.xml配置文件: action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 3 detail 3 0 action *.do index.jsp 前端测试页面: <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html;charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> My JSP 'index.jsp' starting page 倒霉熊-33.rmvb下载 倒霉熊-34.rmvb下载

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。