程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> Struts2上傳下載

Struts2上傳下載

編輯:關於JSP

JSP頁面
<body>
  <s:fielderror></s:fielderror>
  <s:form action="uploadUploadAction" enctype="multipart/form-data"
   theme="simple">
    用戶名:<s:textfield name="userName" />
   <br />
    密碼: <s:textfield name="userPwd" />
   <br />
   <input type="file" name="file" />
   <br />
   <s:submit value="提交"></s:submit>
  </s:form>
  <br />
下載<a href="DownLoadAction">開始.gif</a>
 </body>
UploadAction
 


package com.hyl.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
import com.hyl.util.DateUtil;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
 private File file;
 private String fileFileName;
 private String fileContentType;
 private String userName;
 private String userPwd;

 public String upload() throws IOException {
  String path = ServletActionContext.getRequest().getRealPath("/upload");
  // System.out.println(path);

  InputStream is = new FileInputStream(file);
  String date = DateUtil.mailDate(new java.util.Date());
  // 截取的文件擴展名
  String fileExtenName = fileFileName
    .substring(fileFileName.indexOf('.'));
  // System.out.println("截取的文件擴展名"+fileName);

  File serverFile = new File(path, date + fileExtenName);

  OutputStream os = new FileOutputStream(serverFile);

  byte[] b = new byte[1024];

  int length = 0;

  while ((length = is.read(b)) > 0) {
   os.write(b);

  }
  os.close();
  is.close();
  return SUCCESS;
 }

 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;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getUserPwd() {
  return userPwd;
 }

 public void setUserPwd(String userPwd) {
  this.userPwd = userPwd;
 }

}
DownLoadAction

 

package com.hyl.action;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {
//下面以中文名文件實例
 //此處文件名稱由用戶輸入,此處也是動態傳參的過程
 private String picName = "開始.gif";

 public InputStream getDownLoad() throws UnsupportedEncodingException {
  //此處做一個中間變量,當重新編碼後就無法識別中文名了
  String rourseName=picName;
  //將源文件的中文名重新編碼,目的值讓Struts的配置文件中能識別到,呈現給用戶看
  picName=new String(picName.getBytes(),"iso-8859-1");
 
  System.out.println("/upload/"+rourseName);
 
  return ServletActionContext.getServletContext().getResourceAsStream(
    "/upload/"+rourseName);
 
 }

 public String execute() throws Exception {

  return super.execute();
 }

 public String getPicName() {
  return picName;
 }

 public void setPicName(String picName) {
  this.picName = picName;
 }

}
DateUtil

 

package com.hyl.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil {

 public static String dateTimeChange(Date source) {
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String changeTime = format.format(source);
  return changeTime;
 }

 public static String shortDate(Date aDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
  return formatter.format(aDate);
 }

 public static String nowDate() {
  String iDate = "";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  String str = formatter.format(new Date());
  String[] date = str.split("-");
  if (date.length >= 3) {
   iDate = date[0] + "/" + date[1] + "/" + date[2] + "";
  } else {
   iDate = str;
  }
  return iDate;
 }

 public static String mailDate(Date aDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
  return formatter.format(aDate);
 }

 public static String dateParser(Date aDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  return formatter.format(aDate);
 }

 public static Date parser(String strDate) {
  ;
  strDate = strDate.replace("/", "-");
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  try {
   return sdf.parse(strDate);
  } catch (Exception e) {
   return null;
  }
 }

 public static Date parser(String strDate, String formatter) {
  SimpleDateFormat sdf = new SimpleDateFormat(formatter);
  try {
   return sdf.parse(strDate);
  } catch (Exception e) {
   return null;
  }
 }

 public static String parser(Date date, String formatter) {
  SimpleDateFormat sdf = new SimpleDateFormat(formatter);
  try {
   return sdf.format(date);
  } catch (Exception e) {
   return null;
  }
 }

 public static Date addMonth(Date myDate, int amount) {
  GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(myDate);
  boolean isEndDayOfMonth_old = cal
    .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
    .get(GregorianCalendar.DAY_OF_MONTH);
  cal.add(GregorianCalendar.MONTH, amount);
  boolean isEndDayOfMonth_new = cal
    .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
    .get(GregorianCalendar.DAY_OF_MONTH);
  if (isEndDayOfMonth_old && !isEndDayOfMonth_new) {
   cal.set(GregorianCalendar.DATE, cal
     .getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
  }
  return cal.getTime();
 }

 public static Date addDay(Date myDate, int amount) {
  Calendar cal = Calendar.getInstance();
  cal.setTime(myDate);
  cal.add(Calendar.DAY_OF_MONTH, amount);
  return cal.getTime();
 }

 public static Date addMinute(Date myDate, int amount) {
  Calendar cal = Calendar.getInstance();
  cal.setTime(myDate);
  int minute = 0;
  amount = -(amount);

  if (amount > 60) {

   int hour = (int) amount / 60;

   if (hour * 60 > amount) {
    minute = hour * 60 - amount;

    cal.add(Calendar.HOUR_OF_DAY, -hour);
    cal.add(Calendar.MINUTE, minute);

   } else if (hour * 60 < amount) {

    minute = amount - hour * 60;
    cal.add(Calendar.HOUR_OF_DAY, -hour);
    cal.add(Calendar.MINUTE, -minute);

   } else {
    cal.add(Calendar.HOUR_OF_DAY, -hour);
   }

  } else {

   cal.add(Calendar.MINUTE, -amount);
  }
  return cal.getTime();
 }

 public static Date addYear(Date myDate, int amount) {
  GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(myDate);
  boolean isEndDayOfMonth_old = cal
    .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
    .get(GregorianCalendar.DAY_OF_MONTH);
  cal.add(GregorianCalendar.YEAR, amount);
  boolean isEndDayOfMonth_new = cal
    .getActualMaximum(GregorianCalendar.DAY_OF_MONTH) == cal
    .get(GregorianCalendar.DAY_OF_MONTH);
  if (isEndDayOfMonth_old && !isEndDayOfMonth_new) {
   cal.set(GregorianCalendar.DATE, cal
     .getActualMaximum(GregorianCalendar.DAY_OF_MONTH));
  }
  return cal.getTime();
 }

 public static int getWeekDay(Date myDate) {
  GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(myDate);
  return cal.get(GregorianCalendar.DAY_OF_WEEK);
 }

 public static int getConvertWeekDay(Date myDate) {
  int day = getWeekDay(myDate);
  int result = day - 1;
  if (result == 0)
   result = 7;
  return result;
 }

 public static int getTimeFromDate(Date myDate) {
  SimpleDateFormat sdf = new SimpleDateFormat("hhmmss");
  int result = Integer.parseInt(sdf.format(myDate));
  return result;
 }

 public static long getDaysBetweenDate(Date startDate, Date endDate) {
  Calendar cal = Calendar.getInstance();
  cal.setTime(startDate);
  cal.set(Calendar.HOUR, 0);
  cal.set(Calendar.MINUTE, 0);
  cal.set(Calendar.SECOND, 0);
  cal.set(Calendar.MILLISECOND, 0);
  startDate = cal.getTime();
  cal.setTime(endDate);
  cal.set(Calendar.HOUR, 0);
  cal.set(Calendar.MINUTE, 0);
  cal.set(Calendar.SECOND, 0);
  cal.set(Calendar.MILLISECOND, 0);
  return (cal.getTime().getTime() - startDate.getTime()) / 86400000;

 }

 public static String strDateTime(String str) {
  String idate = "";
  if (str != null) {
   String[] date = str.split("-");
   if (date.length >= 3) {
    idate = date[0] + "." + date[1] + "." + date[2];
   } else {
    idate = str;
   }
  }
  return idate;
 }

 public static String strDotDateTime(String str) {
  String idate = "";
  if (str != null) {
   String data0 = null;
   String[] date = str.split("-");
   if (date.length >= 3) {
    if (date[0] != null) {
     data0 = date[0].substring(2, 4);
    }
    idate = data0 + "." + date[1] + "." + date[2];
   } else {
    idate = str;
   }
  }
  return idate;
 }

 public static String bakDateTime(String str) {
  String idate = "";
  if (str != null) {
   int l1 = str.indexOf(".");
   String d1 = str.substring(0, l1);
   String s1 = str.substring(l1 + 1);
   int l2 = s1.indexOf(".");
   String d2 = s1.substring(0, l2);
   String d3 = s1.substring(l2 + 1);
   idate = d1 + "-" + d2 + "-" + d3;
  }
  return idate;
 }

 public static String strShortDateTime(String str) {
  String idate = "";
  if (str != null) {
   String[] date = str.split("-");
   if (date.length >= 3) {
    idate = date[0] + "." + date[1] + "." + date[2];
   } else {
    idate = str;
   }
   if (idate != null && idate.length() > 9) {
    idate = idate.substring(0, 10);

   }
  }
  return idate;
 }

 public static int getBetweenDayNumber(String dateA, String dateB) {
  long dayNumber = 0;
  long DAY = 24L * 60L * 60L * 1000L;
  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  try {
   java.util.Date d1 = df.parse(dateA);
   java.util.Date d2 = df.parse(dateB);
   dayNumber = (d2.getTime() - d1.getTime()) / DAY;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return (int) dayNumber;
 }

 public static void main(String[] args) {
  System.out.println(nowDate());
 }
}
messageFile.properties

struts.messages.error.file.too.large=\u6587\u4EF6\u8FC7\u5927
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u7C7B\u578B\u4E0D\u4E00\u81F4

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <!--加載Struts的消息資源文件   value裡面指定messageFile.properties的文件名字,不寫擴展名字-->
 <constant name="struts.custom.i18n.resources" value="messageFile"></constant>
 <package name="hyl" extends="struts-default">
  <!-- 上傳的Action -->
  <action name="*UploadAction" class="com.hyl.action.UploadAction"
   method="{1}">
   <result name="success">/ok.jsp</result>
   <result name="input">/index.jsp</result>
   <interceptor-ref name="fileUpload">
    <param name="allowedTypes">image/jpeg</param>
    <param name="maximumSize">102400</param>
   </interceptor-ref>
   <!-- 這個默認的攔截器必須放在自定義攔截器的下面,否則自定義攔截器不能呗調用 -->
   <interceptor-ref name="defaultStack"></interceptor-ref>
  </action>
  <!-- 下載的Action -->
  <action name="DownLoadAction" class="com.hyl.action.DownLoadAction">
   <result name="success" type="stream">
    <!-- 這裡顯示的指定返回類型,像這種能被浏覽器識別的類型會直接顯示出來,
    如果是其他類型,會以下載形式出現,
    如果去掉這個標簽,會啟用默認的text/plain    
     -->  
    <param name="contentType">image/jpeg</param>
    <!-- 此處的方法是Action中的getDownLoad方法, -->
    <param name="inputName">downLoad</param>
    <param name="contentDisposition">filename="${picName}"</param>
    <param name="bufferSize">1024</param>
   </result>
  </action>

 </package>

</struts>   

 


作者:hyljava

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved