基于Struts2环境下的文件上传实例(很简洁的逻辑和代码)

package demo;

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

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author  yeeku.H.lee kongyeeku@163.com
 * @version  1.0
 * <br>Copyright (C), 2005-2008, yeeku.H.Lee
 */

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport
{
 private String title;// 一个备用的JavaBean属性
    private File upload;// 与上传页面中的元素 <input type="file" name="upload" /> 对应即可
    private String uploadContentType; // Struts2的fileUpload拦截器的固有属性
    private String uploadFileName; // Struts2的fileUpload拦截器的固有属性

 //接受依赖注入的属性
    private String savePath;
 //接受依赖注入的Setter方法
    public void setSavePath(String value)
 {
        this.savePath = value;
    }

    @SuppressWarnings("deprecation")
 private String getSavePath() throws Exception
 {
        return ServletActionContext.getRequest().getRealPath(savePath);
    }
   
    public void setTitle(String title) {
       this.title = title;
    }
   
 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 String getTitle() {
    return (this.title);
 }
 public File getUpload() {
  return (this.upload);
 }

 public String getUploadContentType() {
  return (this.uploadContentType);
 }

 public String getUploadFileName() {
  return (this.uploadFileName);
 }
 @Override
    public String execute() throws Exception
 {
  System.out.println("开始上传单个文件....");
  System.out.println("原文件名称:" + getUploadFileName());
  System.out.println("原文件类型:" + getUploadContentType());
  System.out.println("上传文件保存在:"+getSavePath());
  //以服务器的文件保存地址和原文件名建立上传文件输出流
  FileOutputStream fos = new FileOutputStream(getSavePath() + "//" + getUploadFileName());
  FileInputStream fis = new FileInputStream(getUpload());
  byte[] buffer = new byte[4*1024];
  int len = 0;
  while ((len = fis.read(buffer)) > 0)
  {
   fos.write(buffer , 0 , len);
  }
  fis.close();
  fos.close();
        return SUCCESS;
    }
}

 

action的配置如下:

 <!-- 测试文件上传-->
  <action name="uploadAction" class="demo.UploadAction">
    <param name="savePath">/upload</param>
    <result>/demo/upload.jsp</result> 
  </action>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值