1. 程式人生 > >Springmvc上傳單張圖片、多圖片上傳並顯示圖片

Springmvc上傳單張圖片、多圖片上傳並顯示圖片

1、在pom加入jar:

		<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>

2、在Springmvc的配置加入上傳檔案的配置

	<!--預設的mvc註解對映的支援 -->
	<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"/>
		<!-- 最大檔案大小,-1為不限制大小 -->
		<property name="maxUploadSize" value="-1"/>
	</bean>

3、單檔案上傳
當然在一個表單中,需要新增enctype=“multipart/form-data”,一個表單有檔案域,肯定也有基本的文字框,可以一次性提交,springmvc能給我們區別出來,來做不同的處理。首先看下普通的model

package com.ztz.springmvc.model;
 
public class Users {
	private String name;
	private String password;
	//省略get set方法
	
	//重寫toString()方便測試
	@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頁面,並且顯示出上傳圖片:

<%@ 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:

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());
		
		//獲得物理路徑webapp所在路徑
		String pathRoot = request.getSession().getServletContext().getRealPath("");
		String path="";
		if(!file.isEmpty()){
			//生成uuid作為檔名稱
			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";
	}
	//因為我的JSP在WEB-INF目錄下面,瀏覽器無法直接訪問
	@RequestMapping(value="/forward")
	private String forward(){
		return "index";
	}
}

二、 多圖片上傳
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());
		
		//獲得物理路徑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";
	}
}