action 上传文件

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

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.struts2.ServletActionContext;

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

/**
 *
 * @author xiongjitao
 *
 * @version $Rev$
 */
public class ActionFileUpload extends ActionSupport{
 private File upfile;   
    private String fileName;   
    private String contentType;  
    private ServletActionContext context;
    public String execute() throws Exception
    {
     String targetDirectory =ServletActionContext.getServletContext().getRealPath("/");
//     targetDirectory = context.get.getRealPath("/upload");   
        String targetFileName = generateFileName(upfile.getAbsolutePath());   
        File target = new File(targetDirectory, targetFileName);   
           
        copy(upfile, target);  
        return super.execute();
    }
    public File getUpfile() {
  return upfile;
 }
 public void setUpfile(File upfile) {
  this.upfile = upfile;
 }
 public String getFileName() {
  return fileName;
 }
 public void setFileName(String fileName) {
  this.fileName = fileName;
 }
 public String getContentType() {
  return contentType;
 }
 public void setContentType(String contentType) {
  this.contentType = contentType;
 }
 public ServletActionContext getContext() {
  return context;
 }
 public void setContext(ServletActionContext context) {
  this.context = context;
 }
 private String generateFileName(String fileName) {   
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
        String formatDate = format.format(new Date());   
           
        int random = new Random().nextInt(10000);   
           
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
           
        return formatDate + random + extension;   
    }   
    private void copy(File source, File dest) {
        try {
            FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(dest);
             
            byte[] buf = new byte[1024]; 
            int c=-1;
            while((c = fis.read(buf))!=-1)
            {
                fos.write(buf,0,c);
            }
            fos.flush();
            fos.close();
            fis.close();
         
        }
        catch (Exception e) {
           
        }
      }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值