Struts2文件上傳

cnp5 9年前發布 | 4K 次閱讀 Java Struts2

文件上傳使用的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>

 本文由用戶 cnp5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!