Spring4 MVC 多文件上傳(圖片並展示)


開始需要在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()方便測試
    @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>密&nbsp;碼:</label><input type="password" name="password"/><br/>
    <label>頭&nbsp;像</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";
    }
}

1

點擊提交控制台輸出:

Users [name=fileupload, password=test]

2

二、 多圖片上傳

springmvc實現多圖片上傳也很簡單,我們把剛才的例子修改下,在加一個文件域,name的值還是相同

<body>
<form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
    <label>用戶名:</label><input type="text" name="name"/><br/>
    <label>密&nbsp;碼:</label><input type="password" name="password"/><br/>
    <label>頭&nbsp;像1</label><input type="file" name="file"/><br/>
    <label>頭&nbsp;像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";
    }
}

3

4


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM