Struts2文件上传

来源:互联网 发布:linux 按文件名查找 编辑:程序博客网 时间:2024/06/01 10:39

文件上传使用的jar   commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar、

struts.xml 的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.action.extension" value="action,do" />
 <constant name="struts.objectFactory" value="spring" />
 <constant name="struts.custom.i18n.resources" value="mess"/>
 <constant name="struts.i18n.encoding" value="UTF-8"/>
 <constant name="struts.multipart.maxSize" value="20971520" />
       <!-- 文件上传 -->
 <package name="upload" namespace="/upload" extends="struts-default">
     <action name="imageUpload" class="uploadAction" method="execute">
      <param name="allowTypes">
       image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,application/pdf,text/plain
      </param>
      <param name="savePath">/upload</param>
         <result name="success">/WEB-INF/jsp/userlist.jsp</result>
         <result name="input">/WEB-INF/jsp/userlist.jsp</result>
     </action>
 </package>
  </struts>

UploadAction的编写

package frameWork.dzdt.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller("uploadAction")
public class UploadAction extends ActionSupport {
 //上传文件字段名
 private File upload;
 //上传文件的内容类型
 private String uploadContentType;
 //上传文件的名字
 private String uploadFileName;
 //允许上传文件类型 类型格式可以参考tomcat下的web.xml下的配置
 private String allowTypes;
 //上传文件的路径
 private String savePath;
 
 
 public String execute() throws Exception {
  // TODO Auto-generated method stub
  
  String[] fileTypes = this.allowTypes.split(",");
  if(!filterType(fileTypes)){//判断上传文件类型
   ActionContext.getContext().put("message", "文件类型错误");
   return this.INPUT;
  }
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH");
  //组装文件上传的目录为 /upload/2013/10/28/15
  File fileSaveDir = new File(this.getSavePath()+"/"+sdf.format(new Date()));
  if(!fileSaveDir.exists()){//判断文件夹是否存在
   fileSaveDir.mkdirs();
  }
  String ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));//获得文件上传的后缀名
  String fileSaveName = UUID.randomUUID().toString()+ext;//使用uuid作为上传文件的名
  FileOutputStream fos = new FileOutputStream(new File(fileSaveDir,fileSaveName));
  FileInputStream fis = new FileInputStream(upload);
  byte[] buffer = new byte[1024];
  int len = 0;
  while((len = fis.read(buffer))!=-1){//循环写入数据
   fos.write(buffer, 0, len);
  }
  fos.flush();
  fis.close();
  fos.close();
  ActionContext.getContext().put("message", "文件上传成功");
  return this.SUCCESS;
 }

 /**
  * 判断上传的文件类型是否允许
  * @param types
  * @return
  */
 private boolean filterType(String[] types){
  boolean isAllow = false;
  if(types == null){
   return isAllow;
  }
  for(String type:types){//循环判断上传的内容类型是否和配置的文件类型相同
   if(type.equals(uploadContentType)){
    isAllow = true;
    break;
   }
  }
  return isAllow;
 }
 
 public File getUpload() {
  return upload;
 }

 public String getUploadContentType() {
  return uploadContentType;
 }

 public String getUploadFileName() {
  return uploadFileName;
 }

 public String getAllowTypes() {
  return allowTypes;
 }

 public String getSavePath() {
  //根据配置文件配置的savepath获得真实的路径
  return ServletActionContext.getServletContext().getRealPath(this.savePath);
 }

 public void setUpload(File upload) {
  this.upload = upload;
 }

 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }

 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }

 public void setAllowTypes(String allowTypes) {
  this.allowTypes = allowTypes;
 }

 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }

 
}


上传jsp的简单编写

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>upload page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 
  </head>
 
  <body>
   <form action="<%=path %>/upload/imageUpload.do" method="post" enctype="multipart/form-data">
     <input type="file" name="upload">
     <input type="submit" value="上传">
   </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+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'userlist.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   

  </head>
 
  <body>
    upload JSP page. ${message }<br>
  </body>
</html>

 

原创粉丝点击