Struts2中文件上传
- Html界面代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form method="post" action="index" enctype="multipart/form-data"> 文件:<input type="file" name="uploadImage" /><br /> <input type="submit" value="submit"> </form> </body> </html>
- 编写Action部分:
简述:
提供属性并且给出get/set方法
1.uploadImage文件
2.文件名uploadImageFileName
通过函数:FileUtils.copyFile(srcFile, destFile);达到上传目的。
package com.zhangpn.struts2;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
public class Helloworld {
private File uploadImage;
private String uploadImageFileName;
public String execute() {
String reslpath = ServletActionContext.getServletContext().getRealPath("/images");//获取绝对路径
if(uploadImage!=null) {
File savepath = new File(new File(reslpath),uploadImageFileName);//创建保存文件信息
if(!savepath.getParentFile().exists()) {
savepath.getParentFile().mkdirs();
}
try {
FileUtils.copyFile(uploadImage, savepath);
System.out.println("upload success...");
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
public File getUploadImage() {
return uploadImage;
}
public void setUploadImage(File uploadImage) {
this.uploadImage = uploadImage;
}
public String getUploadImageFileName() {
return uploadImageFileName;
}
public void setUploadImageFileName(String uploadImageFileName) {
this.uploadImageFileName = uploadImageFileName;
}
}
凝一眸碧水,拈一缕清风,于一怀静谧中倾听凡尘的落音。
不再奢求什么,做简单的自己,过简单的生活,心在,梦在,你在,便是光阴赐予我的最美。

浙公网安备 33010602011771号