springmvc上傳圖片並顯示圖片--支援多圖片上傳,springmvc上傳圖片

來源:互聯網
上載者:User

springmvc上傳圖片並顯示圖片--支援多圖片上傳,springmvc上傳圖片

實現上傳圖片功能在Springmvc中很好實現。現在我將會展現完整例子。

開始需要在pom.xml加入幾個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>

接下來,在Springmvc的配置加入上傳檔案的配置(PS:我把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>

一、 單檔案上傳

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

package com.ztz.springmvc.model;public class Users {private String name;private String password;//省略get set方法//重寫toString()方便測試@Overridepublic 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:

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());//獲得實體路徑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";}}


點擊提交控制台輸出:

Users [name=fileupload, password=test]


瀏覽器顯示結果:



二、 多圖片上傳

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";}}





著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.