springmvc上传图片并显示图片--支持多图片上传- 转

来源:互联网 发布:js汉字转unicode编码 编辑:程序博客网 时间:2024/06/11 00:01

、 多图片上传

springmvc实现多图片上传也很简单,我们把刚才的例子修改下,在加一个文件域,name的值还是相同

<body>  <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">      <label>用户名:</label><input type="text" name="name"/><br/>      <label>密 码:</label><input type="password" name="password"/><br/>      <label>头 像1</label><input type="file" name="file"/><br/>      <label>头 像2</label><input type="file" name="file"/><br/>      <input type="submit" value="提  交"/>  </form>  </body>  

展示图片来个循环,以便显示多张图片

<body>  <c:forEach items="${imagesPathList}" var="image">      <img src="${basePath}${image}"><br/>  </c:forEach>  </body> 

控制层代码如下:

@Controller  @RequestMapping("/file")  public class FileUploadController {            @RequestMapping(value="/upload",method=RequestMethod.POST)      private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile[] file,              HttpServletRequest request)throws Exception{          //基本表单           System.out.println(users.toString());                    //获得物理路径webapp所在路径           String pathRoot = request.getSession().getServletContext().getRealPath("");          String path="";          List<String> listImagePath=new ArrayList<String>();          for (MultipartFile mf : file) {              if(!mf.isEmpty()){                  //生成uuid作为文件名称                   String uuid = UUID.randomUUID().toString().replaceAll("-","");                  //获得文件类型(可以判断如果不是图片,禁止上传)                   String contentType=mf.getContentType();                  //获得文件后缀名称                   String imageName=contentType.substring(contentType.indexOf("/")+1);                  path="/static/images/"+uuid+"."+imageName;                  mf.transferTo(new File(pathRoot+path));                  listImagePath.add(path);              }          }          System.out.println(path);          request.setAttribute("imagesPathList", listImagePath);          return "success";      }      //因为我的JSP在WEB-INF目录下面,浏览器无法直接访问       @RequestMapping(value="/forward")      private String forward(){          return "index";      }  }  
原文:http://blog.csdn.net/luckey_zh/article/details/46867957




原创粉丝点击