1、HTML代码
<body>
<!--上传一个文件 enctype="multipart/form-data" 上传文件必须设置这个属性和属性值-->
<form action="singleUpload!upload" method="post" enctype="multipart/form-data"> 文件:<s:file name="img"></s:file><br> <input type="submit" value="上传" /> </form> <hr>//对应action代码
public class SingleUploadAction extends ActionSupport implements ServletContextAware {
private ServletContext app; private File img;//收集上传文件 public File getImg() { return img; } public void setImg(File img) { this.img = img; } public String getImgFileName() { return imgFileName; } public void setImgFileName(String imgFileName) { this.imgFileName = imgFileName; } public String getImgContentType() { return imgContentType; } public void setImgContentType(String imgContentType) { this.imgContentType = imgContentType; } private String imgFileName;//固定命名方式,xxxFileName来得到上传的文件名 private String imgContentType;//固定命名方式,xxxContentType得到文件类型; public String upload(){ String path = app.getRealPath("image");//这里我们在WebRoot中建一个image文件夹 File to = new File(path+"\\"+imgFileName);//文件保存的目标位置 try { //将用户上传的文件保存到目标位置 FileUtils.copyFile(img, to); } catch (IOException e) { e.printStackTrace(); } return this.SUCCESS; } public void setServletContext(ServletContext context) { this.app = context; }}
<!--同时上传多个文件-->
<form action="multiUpload!upload" method="post" enctype="multipart/form-data"> 文件:<s:file name="img"></s:file><br> 文件:<s:file name="img"></s:file><br> 文件:<s:file name="img"></s:file><br> <input type="submit" value="上传" /> </form> </body>
//对应action 代码
public class MultiUploadAction extends ActionSupport implements ServletContextAware { private ServletContext app; private File[] img; private String[] imgFileName;//固定命名方式,xxxFileName来得到上传的文件名数组 private String[] imgContentType;//固定命名方式,xxxContentType得到文件类型数组; public File[] getImg() { return img; } public void setImg(File[] img) { this.img = img; } public String[] getImgFileName() { return imgFileName; } public void setImgFileName(String[] imgFileName) { this.imgFileName = imgFileName; } public String[] getImgContentType() { return imgContentType; } public void setImgContentType(String[] imgContentType) { this.imgContentType = imgContentType; } public void setServletContext(ServletContext context) { this.app = context; } public String upload(){ for (int i = 0; i < img.length; i++) { String path = app.getRealPath("image"); File to = new File(path+"\\"+imgFileName[i]);//文件保存的目标位置 try { //将用户上传的文件保存到目标位置 FileUtils.copyFile(img[i], to); } catch (IOException e) { e.printStackTrace(); } } return this.SUCCESS; }}