SpringMVC框架——文件的上传与下载

使用SpringMVC框架做个小练习,需求:

  1、单个图片上传并显示到页面中;

  2、多个图片上传并显示到页面中;

1、pom.xml中添加依赖

    <!-- 文件上传 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

    <!--jstl-->
    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
  </dependencies>

2、编写JSP页面

  • input type 设置为 file  
  • form 表单的 method 设置为 post
  • form 表单的 enctype 设置为 multipart/form-data
      
  • 单文件上传页面upload.jsp
<!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="img"/>
    <input type="submit" value="上传"/><br/>
    <c:if test="${filePath!=null || filePath!=''}">
        <h1>上传的图片</h1>
        <img src="${filePath}" style="width: 300px;">
    </c:if>
</form>
</body>
</html>
  • 多文件上传页面uploadMore.jsp
<!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/uploadMore" method="post" enctype="multipart/form-data">
    file1:<input type="file" name="imgs"/>
    file2:<input type="file" name="imgs"/>
    file3:<input type="file" name="imgs"/>
    <input type="submit" value="上传"/><br/>
    <c:if test="${filePath!=null || filePath!=''}">
        <h1>上传的图片</h1>
        <c:forEach items="${filePaths}" var="img">
            <img src="${img}" style="width: 300px;">
        </c:forEach>
    </c:if>
</form>
</body>
</html>

3、编写controller

package com.sunjian.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/**
 * @author sunjian
 * @date 2020/3/20 8:07
 */
@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(@RequestParam("img")MultipartFile img, HttpServletRequest request){
        System.out.println(img);
        if(img.getSize() > 0){
            // 获取target目录下的文件保存路径
            String path = (String) request.getSession().getServletContext().getRealPath("files");
            System.out.println(path);

            String fileName = img.getOriginalFilename();// 获取原始文件名
            File file = new File(path, fileName); // 创建空文件

            try {
                img.transferTo(file); // 将img中的内容转移到file这个空文件中
            } catch (IOException e) {
                e.printStackTrace();
            }
            request.setAttribute("filePath", "/files/"+fileName);
        }
        return "upload";
    }

    @RequestMapping("/uploadMore")
    public String uploadMore(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request){
        List<String> filePaths = new ArrayList<>();
        for(MultipartFile img:imgs){
            if(img.getSize() > 0){
                String path = request.getSession().getServletContext().getRealPath("files");
                String fileName = img.getOriginalFilename();

                File file = new File(path, fileName);// 创建文件
                try {
                    img.transferTo(file);
                    filePaths.add("/files/" + fileName); // 将文件路径添加到list中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        request.setAttribute("filePaths", filePaths);
        return "uploadMore";
    }
}

4、在springmvc.xml中添加配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 配置自动扫描 -->
    <context:component-scan base-package="com.sunjian.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 消息转换器 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 自定义数据类型转换器 -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.sunjian.converter.DataConverter">
                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
                </bean>
                <bean class="com.sunjian.converter.goodsConverter"></bean>
            </list>
        </property>
    </bean>

    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 处理文件名中文乱码 -->
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 多文件上传总⼤小的上限 10M -->
        <property name="maxUploadSize" value="10485760"></property>
        <!-- 单文件大小的上限 1M -->
        <property name="maxUploadSizePerFile" value="1048576"></property>
    </bean>
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
</beans>

5、启动项目,访问页面上传图片

  http://localhost:7777/upload.jsp

  

  http://localhost:7777/uploadMore.jsp

  

OK.

猜你喜欢

转载自www.cnblogs.com/zuichao123/p/12529526.html
今日推荐