package cn.itcast.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.
struts2.
ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
//批量上传文件
public class Mupload {
private File[] image;// 得到上传的文件
private String[] imageFileName;// 得到上传的文件的名称
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
public String execute() throws Exception {
String realPath = ServletActionContext.getServletContext().getRealPath(
"/m_images");
System.out.println("文件路径: " + realPath);
if (image != null) {
File savedir = new File(realPath);// 获得文件夹
if (!savedir.getParentFile().exists()) {
savedir.getParentFile().mkdirs();
}
for (int i = 0; i < image.length; i++) {
File saveFile = new File(savedir, imageFileName[i]);
FileUtils.copyFile(image[i], saveFile);
}
ActionContext.getContext().put("message", "上传成功");
}
return "success";
}
}
=================================================================
package cn.itcast.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
//单个文件的上传
public class updownd {
private File image;//得到上传的文件
private String imageFileName;//得到上传的文件的名称
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String execute() throws Exception{
String realPath = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realPath);
if(image !=null){
File saveFile = new File(new File(realPath),imageFileName);
if(!saveFile.getParentFile().exists()) saveFile.getParentFile().mkdirs();
FileUtils.copyFile(image, saveFile);
ActionContext.getContext().put("message", "上传成功");
}
return "success";
}
}