package actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File upload; //封装上传文件域的属性
private String uploadContentType; //封装上传文件类型的属性
private String uploadFileName; //封装上传文件名的属性
private String filename; //封装上传文件新文件名的属性
private String uploadPath; //封装上传文件保存在服务器的路径,通过struts.xml中的参数设置
private String result;
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;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
/**
* @return
*/
public String execute() throws Exception{
String fn = "";
//如果新文件名未输入,则使用上传文件的文件名作为服务器保存的文件名
if(filename.equals("")){
fn = uploadPath + uploadFileName;
}
else{
fn = uploadPath + filename;
}
// 如果服务器存在同名的文件,则输出提示信息
if(new File(fn).exists()){
result = "该文件已经存在,请为文件指定一个新的文件名";
}
else{
FileOutputStream fos = new FileOutputStream(fn);
InputStream is = new FileInputStream(upload);
byte[] buffer = new byte[8192]; //每次读8K字节
int count = 0;
while((count = is.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
result = "文件上传成功";
}
return "result";
}
}