struts 2文件下载学习

just posted @ 2009年4月01日 05:58 in struts2 with tags struts2 文件下载 , 1524 阅读

DownloadAction:

 

package com.test.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {

  //必须返回个InputStream
        public InputStream getDownloadFile() {
                return ServletActionContext.getServletContext().getResourceAsStream(
                                "/upload/2.jpg");
        }

        @Override
        public String execute() throws Exception {
                // TODO Auto-generated method stub
                return SUCCESS;
        }
}

 

 

struts.xml:

 

<action name="download" class="com.test.action.DownloadAction">
         <result name="success" type="stream">
                <param name="contentType">image/jpeg</param>
                <param name="contentDisposition">attachment,filename="2.jpg"</param>
                <param name="inputName">downloadFile</param>
         </result>
      </action>

 

 

这里 type 必须为stream,  和struts-default.xml 里面 result-types 的一样
由org.apache.struts2.dispatcher.StreamResult来处理
默认type 为dispatcher。

其中的一些参数 contentType contentDisposition  inputName必须设置
contentDisposition  : attachment,filename="xxx"  浏览器弹出的框框里保存为 就是这个名字
文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件

inputName:  就是在DownloadAction 里面的getDownloadFile方法去掉get,然后首字母小写

下载时的权限问题:
在点下载的时候 可以设置个拦截器来验证


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter