struts2_文件下载

来源:互联网 发布:illustrator cs6 mac 编辑:程序博客网 时间:2024/06/08 02:17

文件下载有两种方式:
其一:通过超链接的方式进行下载。
其二:服务器端编码,通过流向客户端进行回写。
 在这第二种方法中,主要步骤有:

1.通过response设置  response.setContentType(String mimetype);2.通过response设置  response.setHeader("Content-disposition;filename=xxx");3.通过response获取流,将要下载的信息写出。

1.现在来探究struts2框架下,应该怎么样进行方式二的文件下载。

 在struts2中,文件下载是通过struts.xml配置下的action的子标签<result type="stream">完成的。

<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>在StreamResult类中有三个属性:protected String contentType = "text/plain"; //用于设置下载文件的mimeType类型protected String contentDisposition = "inline";//用于设置进行下载操作以及下载文件的名称protected InputStream inputStream; //用于读取要下载的文件。在action类中,定义一个方法:public InputStream getInputStream() throws FileNotFoundException {        FileInputStream fis = new FileInputStream("d:/upload/" + filename);        return fis;}配置stream:<result type="stream">        <param name="contentType">text/plain</param>        <param name="contentDisposition">attachment;filename=a.txt</param>        //会调用当前action中的getInputStream方法。        <param name="inputStream">${inputStream}</param></result>

2. 超链接中文乱码问题

//下载报错<a href="${pageContext.request.contextPath}/download?filename=中国.png">中国.png</a>原因:    超链接是get请求,并且下载的文件是中文名称,会出现中文乱码问题。解决:    将文件名称进行改码,转成UTF-8就好了。    例如:filename = new String(filename.getBytes("iso8859-1","UTF-8"));

3. 下载文件,如何设置配置,让不同文件下载有着不同的名称?
 比如:下载文件后缀名是png,而我们在配置文件中规定就是txt。

在action中进行//设置下载文件mimeType类型public String getContentType() {        String mimeType = ServletActionContext.getServletContext().getMimeType(                filename);        return mimeType;}// 获取下载文件名称public String getDownloadFileName() throws UnsupportedEncodingException {        //使用到了自定义的工具类的方法        return DownloadUtils.getDownloadFileName(ServletActionContext                .getRequest().getHeader("user-agent"), filename);}//自定义的工具类方法public static String getDownloadFileName(String agent, String filename) throws UnsupportedEncodingException {        if (agent.contains("MSIE")) {            // IE浏览器            filename = URLEncoder.encode(filename, "utf-8");        } else if (agent.contains("Firefox")) {            // 火狐浏览器            BASE64Encoder base64Encoder = new BASE64Encoder();            filename = "=?utf-8?B?"                    + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";        } else {            // 其它浏览器            filename = URLEncoder.encode(filename, "utf-8");        }    return filename;}<result type="stream">        <!-- 调用当前action中的getContentType()方法 -->        <param name="contentType">${contentType}</param>         <param name="contentDisposition">attachment;filename=${downloadFileName}</param>        <!-- 调用当前action中的getInputStream()方法 -->        <param name="inputStream">${inputStream}</param></result>

4. 在struts2中进行下载时,如果使用<result type=”stream”>它有缺陷

例如:下载点击后,取消下载,服务器端会产生异常。在开发中,解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。
原创粉丝点击