實現上傳圖片功能在Springmvc中很好實現。如今我將會展示完整例子。html
開始須要在pom.xml加入幾個jar,分別是:java
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
接下來,在Springmvc的配置加入上傳文件的配置(PS:我把springmvc的完整配置都展示出來):web
- <mvc:annotation-driven/>
- <mvc:resources location="/static/" mapping="/static/**" />
- <context:component-scan base-package="com.ztz.springmvc.controller"/>
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
-
- <property name="prefix" value="/WEB-INF/jsp/"/>
-
- <property name="suffix" value=".jsp"/>
- </bean>
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="utf-8"/>
-
- <property name="maxInMemorySize" value="10240"/>
-
- <property name="maxUploadSize" value="-1"/>
- </bean>
1、 單文件上傳
固然在一個表單中,須要添加enctype="multipart/form-data",一個表單有文件域,確定也有基本的文本框,能夠一次性提交,springmvc能給咱們區別出來,來作不一樣的處理。首先看下普通的modelspring
- package com.ztz.springmvc.model;
-
- public class Users {
- private String name;
- private String password;
-
-
-
- @Override
- public String toString() {
- return "Users [name=" + name + ", password=" + password + "]";
- }
- }
這個是表單的JSP頁面:瀏覽器
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- request.setAttribute("basePath", basePath);
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>FileUpload</title>
- </head>
- <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>頭 像</label><input type="file" name="file"/><br/>
- <input type="submit" value="提 交"/>
- </form>
- </body>
- </html>
上傳成功跳轉的JSP頁面,而且顯示出上傳圖片:mvc
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- request.setAttribute("basePath", basePath);
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>頭像</title>
- </head>
- <body>
- <img src="${basePath}${imagesPath}">
- </body>
- </html>
最後是Controller:app
- package com.ztz.springmvc.controller;
-
- import java.io.File;
- import java.util.UUID;
-
- import javax.servlet.http.HttpServletRequest;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
-
- import com.ztz.springmvc.model.Users;
-
- @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());
-
-
- String pathRoot = request.getSession().getServletContext().getRealPath("");
- String path="";
- if(!file.isEmpty()){
-
- String uuid = UUID.randomUUID().toString().replaceAll("-","");
-
- String contentType=file.getContentType();
-
- String imageName=contentType.substring(contentType.indexOf("/")+1);
- path="/static/images/"+uuid+"."+imageName;
- file.transferTo(new File(pathRoot+path));
- }
- System.out.println(path);
- request.setAttribute("imagesPath", path);
- return "success";
- }
-
- @RequestMapping(value="/forward")
- private String forward(){
- return "index";
- }
- }
![](http://static.javashuo.com/static/loading.gif)
點擊提交控制檯輸出:dom
Users [name=fileupload, password=test]
webapp
瀏覽器顯示結果:jsp
![](http://static.javashuo.com/static/loading.gif)
2、 多圖片上傳
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>
控制層代碼以下:
- package com.ztz.springmvc.controller;
-
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
-
- import javax.servlet.http.HttpServletRequest;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
-
- import com.ztz.springmvc.model.Users;
-
- @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());
-
-
- String pathRoot = request.getSession().getServletContext().getRealPath("");
- String path="";
- List<String> listImagePath=new ArrayList<String>();
- for (MultipartFile mf : file) {
- if(!mf.isEmpty()){
-
- 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";
- }
-
- @RequestMapping(value="/forward")
- private String forward(){
- return "index";
- }
- }
![](http://static.javashuo.com/static/loading.gif)