歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Struts2實現同時多文件上傳

Struts2實現同時多文件上傳

日期:2017/3/1 11:08:47   编辑:Linux編程

步驟:

第一步:再WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commns-io-1.32.2.jar

第二步:

  1. <form action="${pageContext.request.contextPath}/control/employee/list_execute.action" enctype="multipart/form-data" method="post">
  2. 文件1:<input type="file" name="image"><br/>
  3. 文件2:<input type="file" name="image"><br/>
  4. 文件3:<input type="file" name="image"><br/>
  5. <input type="submit" value="上傳"/>
  6. </form>
注意:enctype="multipart/form-data" method="post"為固定值

第三步:

  1. public class HelloWorldAction {
  2. private File[] image; //得到上傳文件
  3. private String[] imageFileName; //得到文件的名稱
  4. private String[] imageContentType; //得到文件的類型
  5. public File[] getImage() {
  6. return image;
  7. }
  8. public void setImage(File[] image) {
  9. this.image = image;
  10. }
  11. public String[] getImageFileName() {
  12. return imageFileName;
  13. }
  14. public void setImageFileName(String[] imageFileName) {
  15. this.imageFileName = imageFileName;
  16. }
  17. public String[] getImageContentType() {
  18. return imageContentType;
  19. }
  20. public void setImageContentType(String[] imageContentType) {
  21. this.imageContentType = imageContentType;
  22. }
  23. public String execute() throws Exception{
  24. String realpath = ServletActionContext.getServletContext().getRealPath("/images");
  25. if(image!=null){
  26. File savedir = new File(realpath);
  27. if(!savedir.exists()) savedir.mkdirs();
  28. for(int i = 0 ; i<image.length ; i++){
  29. File savefile = new File(savedir, imageFileName[i]);
  30. FileUtils.copyFile(image[i], savefile);
  31. }
  32. ActionContext.getContext().put("message", "上傳成功");
  33. }
  34. return "success";
  35. }
  36. }
注意:image屬性要和form表單上傳控件名稱要一致
Copyright © Linux教程網 All Rights Reserved