struts2在项目中的应用之普通上传

来源:互联网 发布:mac口红吧 编辑:程序博客网 时间:2024/06/05 23:38

struts2的上传,首先我们需要的是知道导入哪些包

这里用到的主要一个包是commons-fileupload-1.2.2.jar

http://commons.apache.org/proper/commons-fileupload/可以下载

其它需要用到的包包括以下


上传界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib  prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>struts2的上传</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  </head>    <body>     <s:form action="dream/upload.action" theme="simple" enctype="multipart/form-data" method="post">          上传文件:<s:file name="file"></s:file>    <s:submit value="submit"></s:submit>    </s:form>  </body></html>

结果界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib  prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>struts2的上传</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  </head>    <body>  <img alt="" src="<%=path%>/upload/<s:property value="#request.newImgPath"/>" width='220px' height='250px' >    file:<s:property value="#request.newImgPath"/>    fileContentType:<s:property value="fileContentType"/>  </body></html>

action代码

package net.itcast.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;import net.itcast.util.DateUtil;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class UploadAction extends ActionSupport{/* * 成员变量的名称不能随意更改,  * private File file; 变量的名称必须和jsp中上传文件标签中的name属性的值一致. * private String fileFileName;变量的名称必须为"上传文件的名称+FileName". * private String fileContentType;变量的名称必须为"上传文件的名称+ContentType",  */private File file;private String fileFileName;private String fileContentType;public File getFile(){return file;}public void setFile(File file){this.file = file;}public String getFileFileName(){return fileFileName;}public void setFileFileName(String fileFileName){this.fileFileName = fileFileName;}public String getFileContentType(){return fileContentType;}public void setFileContentType(String fileContentType){this.fileContentType = fileContentType;}@SuppressWarnings("deprecation")@Overridepublic String execute() throws Exception{HttpServletRequest request = ServletActionContext.getRequest();int idx = fileFileName.lastIndexOf(".");  //文件后缀  String extention= fileFileName.substring(idx);  String time = DateUtil.getCurrDate("yyyyMMddHHmmssSSS");//新的文件名(日期+后缀)  String newImgPath = time + extention; request.setAttribute("newImgPath", newImgPath);String root = request.getRealPath("/upload");//如果上传目录不存在File dirFile = new File(root);if (!dirFile.exists()) {   dirFile.mkdir();   }//文件读入File destFile = new File(root, newImgPath);InputStream is = new FileInputStream(file);OutputStream os = new FileOutputStream(destFile);byte[] buffer = new byte[1024];int length = 0;while ((length = is.read(buffer))  > 0){os.write(buffer, 0, length);}is.close();os.close();return SUCCESS;}}

如果是多文件上传可以参考下我的上一篇博文,只要把属性设置成list即可,遍历写入图片

这里在说一点,关于写入图片的io代码,如果不想这么累赘可以用FileUtils这个工具类

只需要一行代码:

FileUtils.copyFile(file, destFile);   
如果用到这个工具类,前面的判断上传的文件夹路劲不存在就创建相对应的文件夹代码,都不需要再写,

是不是很方便呢,少些很多代码,开源的东西都不错吧。


限制文件的大小及类型

在文件上传的时候,有可能需要对文件的大小和类型做出限制。Struts2支持直接在fileUpload拦截器上设置参数来进行限制。

       在引用fileUpload拦截器的时候,可以指定三个参数(指定<param>子元素):

  • allowedTypes:指定允许上传的文件的类型,如果存在多种类型,以逗号隔开。注意:这里添的不是文件的扩展名,而是对应的ContentType,如果不知道某种文件的ContentType可以先上传一下试试,在后台输出ContentType来。
  • maximumSize:指定允许上传的文件的最大字节数。
  • allowedExtensions:指定允许上传的文件的扩展名。

如果上传的文件不满足以上的参数指定的条件,则会跳转到一个叫input的<result>上,一般input都会指回到提交之前的页面,也就是文件上传页面。

参数非常简单,但是配置比较怪异,fileUpload拦截器虽然在defaultStack拦截器栈上已经引用了,但是还可以在defaultStack拦截器栈之前再引用一次,然后在这次引用上指定参数,示例代码如下:

<action name="uploadList" class="net.itcast.action.UploadAction">           <result name="success">/uploadsuc.jsp</result>           <!-- 通过拦截器来限制上传图片的类型和大小 -->           <interceptor-ref name="fileUpload">              <param name="allowedTypes">image/bmp,image/x-png,image/gif</param>              <param name="maximumSize">10485760</param>           </interceptor-ref>           <interceptor-ref name="defaultStack"></interceptor-ref>       </action> 



上传超大的文件

Struts2在实现文件上传的时候,还有一个小问题,那就是默认上传文件的大小是不能超过2097152字节的。这个配置在struts2-core-2.1.8.1.jar文件里面,“\org\apache\struts2”文件夹下的default.properties文件里面,配置如下:

struts.multipart.maxSize=2097152  

先来测试一下,看看是不是有这个问题。到文件上传页面,选择一个超过上述字节数的文件来上传看看,点击提交按钮,后台输出错误,示例如下:
org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (3402567) exceeds the configured maximum (2097152)      at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:914)  


注意上面加粗的那句话,明确告诉我们,上传的文件大小为3402567,大于配置的最大值2097152字节。

       那么该怎么办呢?

       方法很简单,只要覆盖这个默认设置就可以了,有两种方式,一种是在struts.properties里面配置,另外一种就是在struts.xml里面配置。这里就以在struts.xml来配置为例,只要在struts.xml中加入如下的常量定义,示例代码如下:

    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->    <constant name="struts.multipart.maxSize" value="10701096"/>
再次测试运行看看,应该就可以正常上传了。

效果图如下:


0 0
原创粉丝点击