Mr.张小白(案例:基于Spring MVC实现文件上传和下载)

基于Spring MVC实现文件上传和下载

一、步骤

1.引入相关依赖pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zjd</groupId>
    <artifactId>chapter13-2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-9</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <dependencies>
        <!--        Spring核心类-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--        Spring MVC-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--        servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--        JSP-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>

</project>

2.搭建Spring MVC环境(配置前端控制器)web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--    配置Spring MVC的前端配置器-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <!--        配置初始化参数,用于读取Spring MVC的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!--        应用加载时创建-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.创建Spring MVC配置文件spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--配置Spring MVC要扫描的包-->
    <context:component-scan base-package="com.zjd"/>
    <!--    配置注解驱动-->
    <mvc:annotation-driven/>
    <!--    配置静态资源的访问映射,此配置中的文件将不被前端控制器拦截-->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <!--    配置视图解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--        设置请求编码格式,必须与JSP中的pageEncoding属性一致,默认为ISO-8859-1-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--        设置允许上传文件的最大值为2M,单位为字节-->
        <property name="maxUploadSize" value="2097152"/>
    </bean>
</beans>

4.创建files.json文件(负责记录我们上传的文件)

在这里插入图片描述

5.创建与files.json内容对应的资源类Resource.java

package com.zjd.pojo;

public class Resource {
    private String name;

    public Resource() {
    }

    public Resource(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

6.创建JSON工具类JSONFileUtils.java

package com.zjd.utils;


import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class JSONFileUtils {
    public static String readFile(String filepath) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(filepath);
        return IOUtils.toString(fileInputStream);
    }

    public static void writeFile(String data, String filepath) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream(filepath);
        IOUtils.write(data, fileOutputStream);
    }
}

7.创建文件控制类FileController.java

package com.zjd.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjd.pojo.Resource;
import com.zjd.utils.JSONFileUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FileController {
    /*
     * 文件上传
     * */
    @RequestMapping("/fileUpLoad")
    public String fileUpLoad(MultipartFile[] files, HttpServletRequest request) throws Exception {
        //设置上传的文件所存放的路径
        String path = request.getServletContext().getRealPath("/") + "files/";
        ObjectMapper mapper = new ObjectMapper();
        if (files != null && files.length > 0) {
            //循环获取上传的文件
            for (MultipartFile file : files) {
                //获取上传文件的名称
                String filename = file.getOriginalFilename();
                ArrayList<Resource> list = new ArrayList<>();
                //读取files.json文件中的文件名称
                String json = JSONFileUtils.readFile(path + "/files.json");
                if (json.length() != 0) {
                    //将files.json的内容转为集合
                    list = mapper.readValue(json, new TypeReference<List<Resource>>() {
                    });
                    for (Resource resource : list) {
                        //如果上传的文件在files.json文件中有同名文件,将当前上传的文件重命名,以避免重名
                        if (filename.equals(resource.getName())) {
                            String[] split = filename.split("\\.");
                            filename = split[0] + "(1)." + split[1];
                        }
                    }
                }
                //文件保存的全路径
                String filePath = path + filename;
                //保存上传的文件
                file.transferTo(new File(filePath));
                list.add(new Resource(filename));
                json = mapper.writeValueAsString(list);//将集合转换成json
                //将上传文件的名称保存在files.json中
                JSONFileUtils.writeFile(json, path + "/files.json");
            }
            request.setAttribute("msg", "(上传成功)");
            return "forward:fileload.jsp";
        }
        request.setAttribute("msg", "(上传失败)");
        return "forward:fileload.jsp";
    }

    @ResponseBody
    @RequestMapping(value = "/getFilesName", produces = "text/html;character=utf-8")
    public String getFilesName(HttpServletRequest request, String response) throws Exception {
        String path = request.getServletContext().getRealPath("/") + "files/files.json";
        String json = JSONFileUtils.readFile(path);
        return json;
    }

    /*
     * 根据浏览器的不同进行编码设置,返回编码后的文件名
     * */
    public String getFileName(HttpServletRequest request, String filename) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String agent = request.getHeader("User-Agent");
        if (agent.contains("Firefox")) {
            //火狐浏览器
            filename = "=?UTF-8?B?" + new String(base64Encoder.encode(filename.getBytes("UTF-8")) + "?=");
        } else {
            //IE及其他浏览器
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        return filename;
    }
    /*
    * 文件下载
    * */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename)throws Exception{
        //指定要下载的文件所在路径
        String path=request.getServletContext().getRealPath("/files/");
        filename =new String(filename.getBytes("ISO-8859-1"),"UTF-8");
        //创建该文件对象
        File file=new File(path+File.separator+filename);
        //设置响应头
        HttpHeaders headers=new HttpHeaders();
        filename=this.getFilesName(request,filename);
        //通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用String MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
}

8.编写文件上传和下载页面fileload.jsp

<%--
  Created by IntelliJ IDEA.
  User: 24360
  Date: 2022/12/4
  Time: 16:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传与下载</title>
    <script src="${pageContext.request.contextPath}/js/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<table border="1">
    <tr>
        <td width="200" align="center">文件上传${msg}</td>
        <td width="300" align="center">下载列表</td>
    </tr>
    <tr>
        <td height="100">
            <form action="${pageContext.request.contextPath}/fileUpLoad" method="post" enctype="multipart/form-data">
                <input type="file" name="files" multiple="multiple"><br/>
                <input type="reset" value="清空"/>
                <input type="submit" value="提交"/>
            </form>
        </td>
        <td id="files"></td>
    </tr>
</table>
</body>
<script>
    $(document).ready(function () {
        var url = "${pageContext.request.contextPath}/getFilesName";
        $.get(url, function (files) {
            var files = eval('(' + files + ')');
            for (var i = 0; i < files.length; i++) {
                $("#files").append("<li><a href=${pageContext.request.contextPath}" + "\\" + "download?filename=" + files[i].name + ">" + files[i].name + "</a></li>");
            }
        })
    })
</script>
</html>

9.引入JSON脚本文件jquery.min.js

在这里插入图片描述

二、项目结构

文件的上传与下载

三、本次完成案例:基于Spring MVC实现文件上传与下载

主要是对文件上传与下载的过程进一步了解并实现

四、重要讯息!!!!!

各位小伙伴有疑问可以私聊我,我会在每周日统一查看回复

路过的小伙伴,该篇文章如果对你有帮助,请留下你的小手(👍)再走哦,

五、下方评论区见该案例源代码

您的支持将是我一直做下去的不竭动力!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值