网站文件上传

来源:互联网 发布:艾克里里淘宝店铺名字 编辑:程序博客网 时间:2024/05/22 11:51

UploadAction.java

package com.test.action;


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


import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;


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


public class UploadAction extends ActionSupport {

/**

*/
private static final long serialVersionUID = -5195472253707222070L;


//定义一个文件对象
    private File file;


    //用于存储文件的文件名
private String fileFileName;




//用于存储文件的文件类型
private String fileContentType;




@Override
public String execute() throws Exception {

//获取文件对象

//将文件对象输入内存
InputStream is = new FileInputStream(this.getFile());
//(这些注释可以被下面三句语句代替)
// //用root存储  文件的存储路径
// String root = ServletActionContext.getRequest().getRealPath("/Upload");
// System.out.print("this.getFileFilename()="+fileFileName);
//
// //目标文件为组成(路径+文件名)
// File destFile = new File(root,this.getFileFileName());
//
// //流文件os,输出目标为destFile
// OutputStream os = new FileOutputStream(destFile);
//
// //缓存块
// byte[] buffer = new byte[400];
// int length = 0;
//
// //数据写入destFile
// while((length = is.read(buffer))>0){
// os.write(buffer,0,length);
// }
//
// is.close();
// os.close();
String root =ServletActionContext.getServletContext().getRealPath("/Upload");
File destFile = new File(root,fileFileName);
FileUtils.copyFile(file, destFile);

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











}

原创粉丝点击