Struts下载和上传

下载页面download.jsp
...
<body>
  <h1>文件下载</h1>
  <ul>
    <li>下载美女图:<a href="download.action">下载图形文件</a></li>
    <li>下载美女文件:<a href="download2.action">下载压缩文件</a></li>
    </ul>
  </body>
...
===================================
上传页面 upload.jsp
...
<body>
  <!-- 错误提示 -->
  <div style="color:red">
   <s:fielderror/>
  </div>
  <form action="upload.action" method="post" enctype="multipart/form-data">
      文件标题:<input type="text" name="title"/><br/>
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
   </form>
  </body>
...
==========================
上传成功页面 succ.jsp
...
<body>
  文件标题:<s:property value=" + title"/><br/><hr/>
  文件为:<img alt="美女" src="<s:property value="'upload/'+uploadFileName"/>"/><br/>
  </body>
...
============================
判断用户是否有权下载input.jsp
...
<body>
  <h1>下载登陆页面</h1>
  ${requestScope.tip }
   <form action="login" method="post">
  <table width="300" align="center">   
    <tr>
     <td>用户名:</td>
     <td><input type="text" name="username"/></td>
    </tr>
    <tr>
     <td>密&nbsp;&nbsp;码:</td>
    <td><input type="text" name="password"/></td>
    </tr>    
    <tr>
    <td><input type="submit" value="登陆"/></td>    
   </tr>   
  </table>
  </form>
  </body>
...

===========UpdateAction==================

package com.zcw.action;

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

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

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
 private String title;
 private File upload;
 private String uploadContentType;
 private String uploadFileName;
 
 private String savePath;
///////////////上传的限制
 private String allowTypes;
 public String getAllowTypes() {
  return allowTypes;
 }
 
 public void setAllowTypes(String allowTypes) {
  this.allowTypes = allowTypes;
 }
 
//////////////////////////////////////// 
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public File getUpload() {
  return upload;
 }
 public void setUpload(File upload) {
  this.upload = upload;
 }
 public String getUploadContentType() {
  return uploadContentType;
 }
 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }
 public String getUploadFileName() {
  return uploadFileName;
 }
 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }
 
 @SuppressWarnings("deprecation")
 public String getSavePath() {
  return ServletActionContext.getRequest().getRealPath(savePath);
 }
 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }
 @Override
 public String execute() throws Exception {
  /////////////////////////////////
  //将允许上传的文件类型的字符串用“,”分隔成字符数组
  String filterResult = this.filterType(this.getAllowTypes().split(","));
  //如果当前文件类型不允许上传
  if(filterResult != null){
   ActionContext.getContext().put("typeError", "您上传的文件类型不正确");
   return filterResult;
  }
  //以服务起器文件保存地址和原文件名建立上传文件输出流
  FileOutputStream fos = new FileOutputStream(this.getSavePath()+
    "//"+this.getUploadFileName());
  //以上传文件建立文件上传流
  FileInputStream fis = new FileInputStream(this.getUpload());
  //将上传文件写到服务器
  byte[] buffer = new byte[1024];
  int len = 0;
  while((len = fis.read(buffer))>0){
   fos.write(buffer,0,len);
  }
  return SUCCESS;
 }
 /////////////////////////////////////
 /**
  * 过滤文件类型
  * @param types 系统所有允许上传的文件类型
  * @return 如果文件类型允许上传返回null否则返回INPUT
  */
 
 public String filterType(String[] types){
  //获取文件属性
  String fileType = this.getUploadContentType();
  for(String type : types){
   if(type.endsWith(fileType)){
    return null;
   }
  }
  return INPUT;
 }
 /////////////////////////////////////
}


=========AuthorityDownAction ===============

package com.zcw.action;

import java.io.InputStream;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class AuthorityDownAction extends ActionSupport {
 private String inputPath;
 public void setInputPath(String inputPath) {
  this.inputPath = inputPath;
 }
 /**
  * 定义一个返回inputstream 的方法作为下载入口
  * 需要配置stream类型结果指定inputName参数
  * @return InputStream
  * @throws Exception
  */
 public  InputStream getTargetFile() throws Exception{
  return ServletActionContext
        .getServletContext()
        .getResourceAsStream(inputPath);
 }
 
 @SuppressWarnings("unchecked")
 @Override
 public String execute() throws Exception {
  ActionContext ctx = ActionContext.getContext();
  //通过ActionContext访问HttpSession
  Map session = ctx.getSession();
  String user =(String)session.get("user");
  if(user != null && user.endsWith("zcw")){
   return SUCCESS;
  }
  ctx.put("tip", "您还未登录或登录的用户名不正确请重新登录");
  return LOGIN;
 }
}

==========LoginAction =================

package com.zcw.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {
 private String username;
 private String password;
 private String tip;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getTip() {
  return tip;
 }
 public void setTip(String tip) {
  this.tip = tip;
 }
 
 @Override
 public String execute() throws Exception {
  if(this.getUsername().equals("zcw")
    && this.getPassword().equals("zcw")
    && (this.getUsername() != null)
    && (this.getPassword() != null)){
   ActionContext.getContext().getSession().put("user", username);
   return SUCCESS;
  }else{
   return LOGIN;
  }
 }
}

========DownloadAction =============

package com.zcw.action;

 

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DownloadAction extends ActionSupport {
 private String inputPath;
 public void setInputPath(String inputPath) {
  this.inputPath = inputPath;
 }
 /**
  * 定义一个返回inputstream 的方法作为下载入口
  * 需要配置stream类型结果指定inputName参数
  * @return InputStream
  * @throws Exception
  */
 public  InputStream getTargetFile() throws Exception{
  return ServletActionContext
        .getServletContext()
        .getResourceAsStream(inputPath);
 }
}
 

-------------------------------struts.xml--------------------------------------------------

<struts>
 <constant name="struts.custom.i18n.resources" value="messageResource"/>
 <constant name="struts.i18n.encoding" value="GBK"></constant>
 <package name="zcw" extends="struts-default">
  <action name="upload" class="com.zcw.action.UploadAction">
  <!-- 配置fileUpload拦截器 -->
  <interceptor-ref name="fileUpload">
   <!-- 配置允许上传文件的类型 -->
   <param name="allowedTypes">
    image/bmp,image/png,image/gif,image/jpeg
   </param>
   <!-- 配置上传文件的大小 -->
   <param name="maximumSize">2000</param>
  </interceptor-ref>
  <!-- 配置系统默认拦截器 -->
  <interceptor-ref name="defaultStack"/>
 
  <!-- 动态设置Action 的属性 -->
   <param name="savePath">/upload</param>
   <result name="success">/succ.jsp</result>
   <!-- 配置有关上传错误的input视图 -->
   <result name="input">/upload.jsp</result>
  </action>
  
  <action name="download" class="com.zcw.action.DownloadAction">
   <!-- 指定下载资源的位置 -->
   <param name="inputPath">/images/haokan.jpg</param>
   <!-- 配置结果类型 为stream-->
   <result name="success" type="stream">
   <!-- 指定下载文件类型 -->
    <param name="contentType">image/jpg</param>
    <!-- 通过getTargetFile()返回下载文件的InputStream -->
    <param name="inputName">targetFile</param>
    <param name="contentDisposition">filename="haokan.jpg"</param>
    <!-- 指定下载文件的缓冲大小 -->
    <param name="bufferSize">4096</param>
   </result>
  </action>
  
  <action name="download2" class="com.zcw.action.AuthorityDownAction">
   <!-- 指定下载资源的位置 -->
   <param name="inputPath">/images/ceshi.rar</param>
   <!-- 配置结果类型 为stream-->
   <result name="success" type="stream">
   <!-- 指定下载文件类型 -->
    <param name="contentType">application/rar</param>
    <!-- 通过getTargetFile()返回下载文件的InputStream -->
    <param name="inputName">targetFile</param>
    <param name="contentDisposition">filename="ceshi.rar"</param>
    <!-- 指定下载文件的缓冲大小 -->
    <param name="bufferSize">4096</param>
   </result>
   <result name="login">/input.jsp</result>
  </action>
  
  <action name="login" class="com.zcw.action.LoginAction">
   <result name="login">/input.jsp</result>
   <result name="success">/download.jsp</result>
  </action>
 </package>
</struts>

-------------------------messageResource_zh_CN.properties--------------------------------------------

loginPage=/u767B/u9646/u9875/u9762
su**age=/u6210/u529F/u9875/u9762
errorPage=/u9519/u8BEF/u9875/u9762
failTip=/u5BF9/u4E0D/u8D77/u60A8/u4E0D/u80FD/u767B/u5F55
user=/u7528/u6237/u540D
pass=/u5BC6/u7801
login=/u767B/u5F55
regist=/u6CE8/u518C
succTip=/u6B22/u8FCE/u60A8/u5DF2/u7ECF/u767B/u5F55
welcomeMsg={0}/uFF0C/u60A8/u597D/uFF01/u73B0/u5728/u65F6/u95F4/u662F{1}/uFF01
struts.messages.error.content.type.not.allowed=/u60A8/u53EA/u80FD/u4E0A/u4F20/u56FE/u7247/u6587/u4EF6
struts.messages.error.file.too.large=/u6587/u4EF6/u592A/u5927/u8D85/u8FC72000kb
struts.messages.error.uploading=/u672A/u77E5/u539F/u56E0/u4E0A/u4F20/u5931/u8D25

 

---------------------------------struts.properties--------------------放在src下自己建------------------------------

struts.multipart.saveDir=/tmp             需要在webroot下建立两个文件夹update(上传目录)images(里面是要下载的文件)

猜你喜欢

转载自blog.csdn.net/wang5990302/article/details/22726995