当前位置: 移动技术网 > IT编程>开发语言>Java > java中Struts2文件上传问题详解

java中Struts2文件上传问题详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

首先是网页部分,upload_file.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!doctype html>
<html>
<head>
<title>upload file</title>
</head>
<body>
  <form action="uploadfile" method="post" enctype="multipart/form-data">
    <!--文件域-->
    <input type="file" name="source" /> <input type="submit" value="上传">
  </form>
</body>
</html>

上传文件的表单,metho必须设置成post,enctype必须设置成multipart/form-data。

从上面代码中可以看到这个表单提交给了uploadfile这个action来处理,那我们在struts.xml里面配置如下:

<action name="uploadfile" class="com.lidi.action.uploadaction">
  <result name="success">/uploadresult.jsp</result>
  <!--fileupload拦截器,可用于限制上传文档的类型和文档大小 -->
  <interceptor-ref name="fileupload">
  <!-- 限制文件大小20m,单位为字节 -->
    <param name="maximumsize">20971520</param>
  </interceptor-ref>
  <!--默认拦截器,必须声明在fileupload拦截器之后 -->
  <interceptor-ref name="defaultstack" />
 </action>

fileupload拦截器,用于设置上传路径,限制文件类型和大小。

关于限制文件大小,光有<param name="maximumsize">是不行的,还必须在<struts>标签下添加

<constant name="struts.multipart.maxsize" value="21000000"/>

这行代码表示整个项目所有要上传文件的地方允许上传的文件大小的最大值,也就是说这个项目里上传的任何单个文件大小不能超过21000000字节(约20m),如果项目中不添加这行代码,则默认允许上传的文件大小最大为2m,所以这也是突破struts2只能上传2m文件的限制的方法。

关于限制文件类型,如果需要限制为图片文件,则<interceptor>可以这样配置

<!-- 设置只允许上传图片文件 -->
<intercepter-ref name="fileupload">
  <param name="allowedtypes">image/bmp, image/x-png, image/gif, image/jpeg</param>
</intercepter-ref>
<interceptor-ref name="defaultstack" />

<param name="allowedtypes">标签中的值都是文件的mime类型,常用文件的mime类型可以在%tomcat_home%\conf\web.xml中找到。

如果要限制为word文件,则可以<interceptor>可以这样配置

<!-- 设置只允许上传word文档 -->
<intercepter-ref name="fileupload">
  <param name="allowedtypes">application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
</intercepter-ref>
<interceptor-ref name="defaultstack" />

然而我感觉这样来限制文件类型,不如用javascript在前端实现限制。

接下来写uploadaction,uploadaction必需的私有属性是source,这是和upload_file.jsp里面文件域的name属性是一致,就是说文件域的name属性值为source,则uploadaction中必需有私有属性source,另外,还有两个比较重要的私有属性:

private string sourcefilename; //待上传文件的文件名
private string sourcecontenttype; //待上传文件的文件类型
这两个变量名的格式就是前面的前缀source和upload_file.jsp中的文件域的name属性相同。

综合来说,就是,比如upload_file.jsp中文件域的name = “abc”,则action中就需要这样定义

private file abc;
private string abcfilename;
private string abccontenttype; 

abc会自动获取要上传的文件对象,abcfilename自动获取文件名,abccontenttype自动获取文件类型。

关于上传路径,是我要重点说一下的。

如果是上传到绝对路径,那还挺好搞的,但如果要上传到项目根目录下的upload文件夹呢,怎么获得这个upload文件夹的完整路径?

我尝试过使用

servletactioncontext.getservletcontext().getrealpath("/upload");
但返回了null。也用过

servletactioncontext.getrequest().getrealpath("/upload");
还是返回了null。但在网上查下这个问题,很多人都推荐这么写,证明可能某些情况下这样写确实是可行的,但也有跟我一样返回null的人,他们同时推荐了一种新的方法,就是让uploadaction实现servletcontextaware接口。具体做法如下:

public class uploadaction extends actionsupport implements servletcontextaware {

  /**
   * 省略其它代码...
   */
  private servletcontext context; 

  public servletcontext getcontext() {
    return context;
  }

  public void setcontext(servletcontext context) {
    this.context = context;
  }
  
  @override
  public void setservletcontext(servletcontext context) {
    this.context = context;
  }
}

然后使用

string path = context.getrealpath("/upload");// 重要:斜杠不能少

获得upload文件夹的路径。然后执行上传:

/*将文件上传到upload文件夹下*/
file savefile = new file(path, sourcefilename);
fileutils.copyfile(source, savefile);

我个人是比较推荐这种方法的,因为这种方法好像规避了当项目被打包转移到其它环境时也能保证获得正确的路径。

后面贴上uploadaction的完整代码uploadaction.java

package com.lidi.action;
import java.io.file;
import java.io.ioexception;
import javax.servlet.servletcontext;
import org.apache.commons.io.fileutils;
import org.apache.struts2.util.servletcontextaware;
import com.opensymphony.xwork2.actionsupport;
public class uploadaction extends actionsupport implements servletcontextaware {
  /**
   * 
   */
  private static final long serialversionuid = 1l;
  private file source;// 待上传文件
  private string sourcefilename;// 待上传文件的文件名
  private string sourcecontenttype; // 待上传文件的文件类型
  private servletcontext context; // 重要
  /* 重要 */
  public servletcontext getcontext() {
    return context;
  }
  public void setcontext(servletcontext context) {
    this.context = context;
  }
  /* getters & setters */
  public file getsource() {
    return source;
  }
  public void setsource(file source) {
    this.source = source;
  }
  public string getsourcefilename() {
    return sourcefilename;
  }
  public void setsourcefilename(string sourcefilename) {
    this.sourcefilename = sourcefilename;
  }
  public string getsourcecontenttype() {
    return sourcecontenttype;
  }
  public void setsourcecontenttype(string sourcecontenttype) {
    this.sourcecontenttype = sourcecontenttype;
  } 
  @override
  public void setservletcontext(servletcontext context) {
    this.context = context;
  }
  public string execute() throws ioexception {
    /*获取存放上传文件的路径:项目根目录upload文件夹*/
    string path;
    path = context.getrealpath("/upload");// 重要:斜杠不能少
    system.out.println(path);    
    /*将文件上传到upload文件夹下*/
    file savefile = new file(path, sourcefilename);
    fileutils.copyfile(source, savefile);
    system.out.println(savefile.getabsolutepath());
    return success;
  }
}

上传结果页uploadresult.jsp

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!doctype html>
<html>
 <head>  
  <title>upload result</title>
 </head>
 <body>
 <p>文件名:<s:property value="sourcefilename" /></p>
 <p>文件类型:<s:property value="sourcecontenttype" /></p>
 <p>文件:<a href="upload/<s:property value="sourcefilename" />"><s:property value="sourcefilename" /></a></p>
 </body>
</html>

以上所述就是本文的全部内容了,希望大家能够喜欢。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网