struts2中文件上传与下载

来源:互联网 发布:源计划亚索多少钱淘宝 编辑:程序博客网 时间:2024/06/05 07:21

--struts2中文件上传的二个限制,一个是struts.multipart.maxSize,如果不设置,struts2 的核心包下的default.properties文件里有默认的大小设置struts.multipart.maxSize=2097152,即2M. 这是struts2文件上传的第一道关.

第二道关是inteceptor中的maximumSize. 当真实的文件大小能通过第一道关时.针对不同的action中配置的inteceptor,maximumSize才能发挥相应的拦截作用.

比如struts.multipart.maxSize=50M. actionA中inteceptorA的maximumSize=30M. actionB中inteceptorB的maximumSize=10M.

struts.multipart.maxSize=50M对于inteceptorA,B都会起到第一关的作用.而inteceptorA和inteceptorB可以在通过第一关之后,根据自己的业务定制各自针对拦截器起作用的maximumSize

如果真实的文件>50M. 抛出会抛出the request was rejected because its size (XXXX) exceeds the configured maximum (XXXX)异常,他是不能被国际化的,因为这个信息是commons-fileupload组件抛出的,是不支持国际化这信息.

struts2.2 org.apache.commons.fileupload.FileUploadBase.java中

复制代码
/**
* Creates a new instance.
*
@param ctx The request context.
*
@throws FileUploadException An error occurred while
* parsing the request.
*
@throws IOException An I/O error occurred.
*/
FileItemIteratorImpl(RequestContext ctx)
throws FileUploadException, IOException {
if (ctx == null) {
throw new NullPointerException("ctx parameter");
}

String contentType
= ctx.getContentType();
if ((null == contentType)
|| (!contentType.toLowerCase().startsWith(MULTIPART))) {
throw new InvalidContentTypeException(
"the request doesn't contain a "
+ MULTIPART_FORM_DATA
+ " or "
+ MULTIPART_MIXED
+ " stream, content type header is "
+ contentType);
}

InputStream input
= ctx.getInputStream();

if (sizeMax >= 0) {
int requestSize = ctx.getContentLength();
if (requestSize == -1) {
input
= new LimitedInputStream(input, sizeMax) {
protected void raiseError(long pSizeMax, long pCount)
throws IOException {
FileUploadException ex
=
new SizeLimitExceededException(
"the request was rejected because"
+ " its size (" + pCount
+ ") exceeds the configured maximum"
+ " (" + pSizeMax + ")",
pCount, pSizeMax);
throw new FileUploadIOException(ex);
}
};
}
else {
///问题就在这里////////////////////////////////////
if (sizeMax >= 0 && requestSize > sizeMax) {
throw new SizeLimitExceededException(
"the request was rejected because its size ("
+ requestSize
+ ") exceeds the configured maximum ("
+ sizeMax + ")",
requestSize, sizeMax);
}
}
}

String charEncoding
= headerEncoding;
if (charEncoding == null) {
charEncoding
= ctx.getCharacterEncoding();
}

boundary
= getBoundary(contentType);
if (boundary == null) {
throw new FileUploadException(
"the request was rejected because "
+ "no multipart boundary was found");
}

notifier
= new MultipartStream.ProgressNotifier(listener,
ctx.getContentLength());
multi
= new MultipartStream(input, boundary, notifier);
multi.setHeaderEncoding(charEncoding);

skipPreamble
= true;
findNextItem();
复制代码

如果InteceptorA上传的是40M的真实文件.那么此时拦截器InteceptorA会访问国际化信息:struts.messages.error.file.too.larges对应的值.

当且仅当上传文件<=30M的时候,InteceptorA才会成功上传.

下面是解决struts.multipart.maxSize提示信息不友好的问题.

当超过50M时.commons-fileupload抛出运行时异常,struts2会把这个异常看到是action级别的异常.所以会将异常信息

the request was rejected because its size (XXXX) exceeds the configured maximum (XXXX)写到actionError里面.我们需要做的就是在action里覆盖addActionError方法

复制代码
@Override
public void addActionError(String anErrorMessage) {
//改从国际化里取值
if (anErrorMessage
.startsWith(
"the request was rejected because its size")) {
super.addActionError(getText("struts.multipart.maxSize.limit"));
}
else {
super.addActionError(anErrorMessage);
}
}
复制代码

相应的配置文件

struts.multipart.maxSize.limit=系统上传的文件最大为50M
struts.messages.error.file.too.larges=新广告批量上传的文件最大为5M
struts.messages.error.content.type.not.allowed=上传的文件格式目前仅支持xls格式
struts.messages.error.uploading=上传文件失败
struts.messages.invalid.token=您已经提交了表单,请不要重复提交。
fileupload.filenums.exceed=已经有超过5个文件在运行,请稍候再试
filedownload.rows.exceed=由于您选择的广告组内广告数量太多,请分组下载
accountNotExist=客户不存在
invalidTask=无效的任务

注意,由于inteceptor中途返回,原来页面上输入的其他文本内容也都不见了,也就是说params注入失败。

 

这个是没办法的,因为这个异常是在文件上传之前捕获的,文件未上传,同时params也为注入,所以这时最好重定向到一个jsp文件,提示上传失败,然后重写填写相应信息。

解决办法:最好跳到一个专门显示错误的页.而不要返回操作页.

-------------------------------------------------------------------------------------------

注意,拦截器所谓的同名配置覆盖,是重复执行的,比如defaultStack中是包含fileUpload,token的. 如果将<interceptor-ref name="defaultStack" />放到显示定义的拦截器之后,会覆盖显示定义的拦截器.

下面是正确的拦截器顺序:

复制代码
<action name="BatchMIADOperation!*" method="{1}"
class
="com.*****.***.action.multiidea.batchad.BatchMIADOperationAction">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">5242880</param>
<!--
<param name="allowedTypes">
application/vnd.ms-excel
</param>
-->
</interceptor-ref>
<interceptor-ref name="token">
<param name="excludeMethods">
init,search,updateBatchCpcMatch,batchExportMIAD,downloadWhenError
</param>
</interceptor-ref>
<result name="input">
/WEB-INF/jsp/multiidea/batchad/BatchMIAD.jsp
</result>
<result name="success">
/WEB-INF/jsp/multiidea/batchad/BatchMIAD.jsp
</result>
<result name="invalid.token">
/WEB-INF/jsp/multiidea/batchad/BatchMIAD.jsp
</result>
</action>

复制代码


Struts下载文件设置**********************

一、    Struts2 实现文件下载

使用Struts2框架来控制文件的下载,关键是需要配置一个stream类型的结果,需要指定下面4个属性:

  contentType属性:指定被下载文件的文件类型。 和互联网MIME标准中的规定类型一致,如text/plain代表纯文本,text/xml代表XML,image/gif代表GIF图片,iamge/jpeg代表JPG图片

  inputName属性: 指定被下载文件的入口输入流。 例如,下面定义的Action的下载文件输入流入口为getTargetFile()方法,所以这里要相应的指定为targetFile。

  contentDisposition属性:指定文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件。比如取值为:

                       attachment;filename="test.jpg",表示文件下载的时候保存的名字为test.jpg。如果直接写filename="test.jpg",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于如下写法:inlinefilename="test.jpg".

  bufferSize属性: 指定下载文件时缓冲区大小。

 

配置上面4个属性,既可以在配置文件中配置,也可以在Action中设置该属性来完成配置。


二、    在配置文件中指定下载资源

1、    文件下载业务控制器

 

   public class MyDownload extends ActionSupport {

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    private String inputPath;

    public void setInputPath(String inputPath) {

       this.inputPath = inputPath;

    }

    //根据配置文件inputPath属性值返回一个InputStream类型值

    public InputStream getTargetFile() throws Exception{

return ServletActionContext.getServletContext()

.getResourceAsStream(inputPath);

    }  

    public String execute()throws Exception{

       return SUCCESS;

    }

}

   

2、    相应的Action的配置:

 

        <action name="download" class="download.MyDownload">

            <!—指定资源下载位置 -->

           <param name="inputPath">/download/xiao.jpg</param>

            <!—指定success逻辑视图为一个stream类型,即流视图 -->

           <result name="success" type="stream">

            

                <!—下载文件类型 -->

              <param name="contentType">iamge/jpg</param>

                 <!—下载文件位置 -->

              <param name="inputName">targetFile</param>

              <param name="contentDisposition">

filename="hello.jpg"

</param>

 <!—缓冲区大小 -->

              <param name="bufferSize">2000000</param>

           </result>

       </action>

 

 

三、    在Action中指定下载资源(动态指定下载资源)

1、    动态指定下载资源的业务控制器

 

    public class Ddownload extends ActionSupport {

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    private String inputPath;// 下载文件的入口输入流

    private String contentType;//文件类型

    private String filename;//指定下载后的文件名

   

    public void setInputPath(String inputPath) {

       this.inputPath = inputPath;

    }

    public String getContentType() {

       return contentType;

    }

    public void setContentType(String contentType) {

        this.contentType = contentType;

    }

    public String getFilename() {

       return filename;

    }

    public void setFilename(String filename) {

       this.filename = filename;

    }

 

 

 

    public InputStream getTargetFile() throws Exception{

          return ServletActionContext.getServletContext()

.getResourceAsStream(inputPath);

    }

   

    public String execute()throws Exception{

       //调用相关业务逻辑方法,动态设置相关下载信息

       inputPath="/download/xiao.jpg";

       filename="test.jpg";

       contentType="image/jpg";

 

       return SUCCESS;

    }

}

 

2、    相应的Action配置文件

 

              <action name="Ddownload" class="download.Ddownload">

           <result name="success" type="stream">

              <param name="contentType">${contentType}</param>

              <param name="inputName">targetFile</param>

              <param name="contentDisposition">

filename="${filename}"

</param>

              <param name="bufferSize">2000000</param>

           </result>

      </action>

 

四、     文件下载的权限控制

明白了Struts2框架文件下载的原理后,就很容易实现文件下载的权限控制,可以在Action的execute()方法中加入用户合法身份的验证。当然,也可以使用拦截器来实现权限的控制,在拦截器中通过检查session对象同样可以限制权限。

五、参数解释

其中主要使用的参数是:
contentType 指定下载文件的文件类型 —— application/octet-stream 表示无限制
inputName 流对象名 —— 比如这里写inputStream,它就会自动去找Action中的getInputStream方法。
contentDisposition 使用经过转码的文件名作为下载文件名 —— 默认格式是attachment;filename="${fileName}",将调用该Action中的getFileName方法。
bufferSize 下载文件的缓冲大小



* 注意使用getResourceAsStream方法时,文件路径必须是以“/”开头,且是相对路径。这个路径是相对于项目根目录的。
* 可以用return new FileInputStream(fileName)的方法来得到绝对路径的文件。

在WEB-INF下随意丢一个test.txt,部署好后进入浏览器,输入tomcat地址/项目路径/download.action?fileName=test.txt即可下载到该文件。

附:contentType类型.
'ez' => 'application/andrew-inset', 
'hqx' => 'application/mac-binhex40', 
'cpt' => 'application/mac-compactpro', 
'doc' => 'application/msword', 
'bin' => 'application/octet-stream', 
'dms' => 'application/octet-stream', 
'lha' => 'application/octet-stream', 
'lzh' => 'application/octet-stream', 
'exe' => 'application/octet-stream', 
'class' => 'application/octet-stream', 
'so' => 'application/octet-stream', 
'dll' => 'application/octet-stream', 
'oda' => 'application/oda', 
'pdf' => 'application/pdf', 
'ai' => 'application/postscript', 
'eps' => 'application/postscript', 
'ps' => 'application/postscript', 
'smi' => 'application/smil', 
'smil' => 'application/smil', 
'mif' => 'application/vnd.mif', 
'xls' => 'application/vnd.ms-excel', 
'ppt' => 'application/vnd.ms-powerpoint', 
'wbxml' => 'application/vnd.wap.wbxml', 
'wmlc' => 'application/vnd.wap.wmlc', 
'wmlsc' => 'application/vnd.wap.wmlscriptc', 
'bcpio' => 'application/x-bcpio', 
'vcd' => 'application/x-cdlink', 
'pgn' => 'application/x-chess-pgn', 
'cpio' => 'application/x-cpio', 
'csh' => 'application/x-csh', 
'dcr' => 'application/x-director', 
'dir' => 'application/x-director', 
'dxr' => 'application/x-director', 
'dvi' => 'application/x-dvi', 
'spl' => 'application/x-futuresplash', 
'gtar' => 'application/x-gtar', 
'hdf' => 'application/x-hdf', 
'js' => 'application/x-javas

cript', 
'skp' => 'application/x-koan', 
'skd' => 'application/x-koan', 
'skt' => 'application/x-koan', 
'skm' => 'application/x-koan', 
'latex' => 'application/x-latex', 
'nc' => 'application/x-netcdf', 
'cdf' => 'application/x-netcdf', 
'sh' => 'application/x-sh', 
'shar' => 'application/x-shar', 
'swf' => 'application/x-shockwave-flash', 
'sit' => 'application/x-stuffit', 
'sv4cpio' => 'application/x-sv4cpio', 
'sv4crc' => 'application/x-sv4crc', 
'tar' => 'application/x-tar', 
'tcl' => 'application/x-tcl', 
'tex' => 'application/x-tex', 
'texinfo' => 'application/x-texinfo', 
'texi' => 'application/x-texinfo', 
't' => 'application/x-troff', 
'tr' => 'application/x-troff', 
'roff' => 'application/x-troff', 
'man' => 'application/x-troff-man', 
'me' => 'application/x-troff-me', 
'ms' => 'application/x-troff-ms', 
'ustar' => 'application/x-ustar', 
'src' => 'application/x-wais-source', 
'xhtml' => 'application/xhtml+xml', 
'xht' => 'application/xhtml+xml', 
'zip' => 'application/zip', 
'au' => 'audio/basic', 
'snd' => 'audio/basic', 
'mid' => 'audio/midi', 
'midi' => 'audio/midi', 
'kar' => 'audio/midi', 
'mpga' => 'audio/mpeg', 
'mp2' => 'audio/mpeg', 
'mp3' => 'audio/mpeg', 
'aif' => 'audio/x-aiff', 
'aiff' => 'audio/x-aiff', 
'aifc' => 'audio/x-aiff', 
'm3u' => 'audio/x-mpegurl', 
'ram' => 'audio/x-pn-realaudio', 
'rm' => 'audio/x-pn-realaudio', 
'rpm' => 'audio/x-pn-realaudio-plugin', 
'ra' => 'audio/x-realaudio', 
'wav' => 'audio/x-wav', 
'pdb' => 'chemical/x-pdb', 
'xyz' => 'chemical/x-xyz', 
'bmp' => 'image/bmp', 
'gif' => 'image/gif', 
'ief' => 'image/ief', 
'jpeg' => 'image/jpeg', 
'jpg' => 'image/jpeg', 
'jpe' => 'image/jpeg', 
'png' => 'image/png', 
'tiff' => 'image/tiff', 
'tif' => 'image/tiff', 
'djvu' => 'image/vnd.djvu', 
'djv' => 'image/vnd.djvu', 
'wbmp' => 'image/vnd.wap.wbmp', 
'ras' => 'image/x-cmu-raster', 
'pnm' => 'image/x-portable-anymap', 
'pbm' => 'image/x-portable-bitmap', 
'pgm' => 'image/x-portable-graymap', 
'ppm' => 'image/x-portable-pixmap', 
'rgb' => 'image/x-rgb', 
'xbm' => 'image/x-xbitmap', 
'xpm' => 'image/x-xpixmap', 
'xwd' => 'image/x-xwindowdump', 
'igs' => 'model/iges', 
'iges' => 'model/iges', 
'msh' => 'model/mesh', 
'mesh' => 'model/mesh', 
'silo' => 'model/mesh', 
'wrl' => 'model/vrml', 
'vrml' => 'model/vrml', 
'css' => 'text/css', 
'html' => 'text/html', 
'htm' => 'text/html', 
'asc' => 'text/plain', 
'txt' => 'text/plain', 
'rtx' => 'text/richtext', 
'rtf' => 'text/rtf', 
'sgml' => 'text/sgml', 
'sgm' => 'text/sgml', 
'tsv' => 'text/tab-separated-values', 
'wml' => 'text/vnd.wap.wml', 
'wmls' => 'text/vnd.wap.wmlscript', 
'etx' => 'text/x-setext', 
'xsl' => 'text/xml', 
'xml' => 'text/xml', 
'mpeg' => 'video/mpeg', 
'mpg' => 'video/mpeg', 
'mpe' => 'video/mpeg', 
'qt' => 'video/quicktime', 
'mov' => 'video/quicktime', 
'mxu' => 'video/vnd.mpegurl', 
'avi' => 'video/x-msvideo', 
'movie' => 'video/x-sgi-movie', 
'ice' => 'x-conference/x-cooltalk'


0 0
原创粉丝点击