以上是jsp的代码
下面看action的代码
private File upload;
private String uploadContentType;
private String uploadFileName;
private String filename;
private String uploadPath; //上传文件保存在服务器的路径,通过参数设置
private String result;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = 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 execute() throws Exception{
String fn = "";
//如果新文件名未输入,则使用上传文件的文件名作为服务器保存的文件名
if(filename.equals("")){
fn = uploadPath + uploadFileName; //获得上传的文件名
}else{
fn = uploadPath + filename;
}
System.out.println(uploadContentType);
//如果服务器存在同名的文件,则输出提示信息
if(new File(fn).exists()){
result = "该文件已经存在,请为其指定一个新的文件名!";
}else{
FileOutputStream fos = new FileOutputStream(fn);
InputStream is = new FileInputStream(upload);
byte[] buffer = new byte[8192];
int count = 0;
while((count = is.read(buffer))>0){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
result = "文件上传成功";
}
return "result";
}
}
这是action的代码,其余的都不用解释,但是有几个命名要解释一下。
主要是这个uploadFileName和uploadContentType是怎样接收到值的,
在struts中:xxxFileName: 该属性 封装了文件域中的文件名,为String类型。其中xxx表示上传域的name的属性值,在本例中xxxFileName属性值就是uploadFileName
对于xxxContentType的原理也是一样的
至于action的配置很简单
result.jsp的代码更是简单