欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC实现文件上传下载的全过程

程序员文章站 2022-03-04 13:41:51
目录前言一、通用配置二、实现文件下载,上传功能总结前言文件的上传和下载都是基于io复制,只不过文件上传是浏览器向服务器发送报文文件下载是服务器向浏览器发送报文提示:以下是本篇文章正文内容,下面案例可供...

前言

文件的上传和下载都是基于io复制,只不过

文件上传是浏览器向服务器发送报文

文件下载是服务器向浏览器发送报文

提示:以下是本篇文章正文内容,下面案例可供参考

SpringMVC实现文件上传下载的全过程

一、通用配置

SpringMVC实现文件上传下载的全过程

pom.xml

    <dependencies>
        <!-- springmvc -->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-webmvc</artifactid>
            <version>5.3.13</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupid>ch.qos.logback</groupid>
            <artifactid>logback-classic</artifactid>
            <version>1.2.3</version>
        </dependency>

        <!-- servletapi -->
        <dependency>
            <groupid>javax.servlet</groupid>
            <artifactid>javax.servlet-api</artifactid>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- spring5和thymeleaf整合包 -->
        <dependency>
            <groupid>org.thymeleaf</groupid>
            <artifactid>thymeleaf-spring5</artifactid>
            <version>3.0.12.release</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupid>commons-fileupload</groupid>
            <artifactid>commons-fileupload</artifactid>
            <version>1.3.1</version>
        </dependency>
<!--        springmvc end-->

        <!--    导入spring坐标-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-context</artifactid>
            <version>5.3.11</version>
        </dependency>
<!--        导入测试坐标-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--    测试坐标-->
<!--        导入集成测试坐标-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-test</artifactid>
            <version>5.3.13</version>
        </dependency>
        <!--        集成测试坐标end-->
        <!--        导入mysql坐标-->
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
            <version>8.0.24</version>
        </dependency>
        <!--        mysql坐标end-->
        <!--        导入druid连接池-->
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>druid</artifactid>
            <version>1.2.8</version>
        </dependency>
        <!--        导入druid连接池end-->
        <!--        导入spring上下文-->
        <dependency>
            <groupid>org.springframework</groupid>
            <artifactid>spring-context</artifactid>
            <version>5.3.11</version>
        </dependency>
        <!--        导入spring上下文end-->
<!--        导入spring web开发api start-->
        <dependency>
            <groupid>javax.servlet</groupid>
            <artifactid>javax.servlet-api</artifactid>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupid>javax.servlet.jsp</groupid>
            <artifactid>javax.servlet.jsp-api</artifactid>
            <version>2.3.3</version>
        </dependency>
        <!--        导入spring web开发end-->
<!--        导入jackson的依赖-->
        <dependency>
            <groupid>com.fasterxml.jackson.core</groupid>
            <artifactid>jackson-databind</artifactid>
            <version>2.12.1</version>
        </dependency>
        <!--上传功能的关键jar -->
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupid>commons-fileupload</groupid>
            <artifactid>commons-fileupload</artifactid>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

上传功能的关键jar

SpringMVC实现文件上传下载的全过程

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">
    <!--配置springmvc的编码过滤器-->
    <!--    springmvc中处理编码的过滤器一定要配置到其他过滤器之前,否则无效-->
    <!-- 字符集过滤器 -->
    <filter>
        <description>字符集过滤器</description>
        <filter-name>characterencodingfilter</filter-name>
        <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
        <init-param>
            <description>字符集编码</description>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceencoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <!-- 字符集拦截 -->
    <filter-mapping>
        <filter-name>characterencodingfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <filter>
        <filter-name>hiddenhttpmethodfilter</filter-name>
        <filter-class>org.springframework.web.filter.hiddenhttpmethodfilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenhttpmethodfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--    注册前端控制器dispatcherservlet-->
    <servlet>
        <servlet-name>dispatcherservlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
        <init-param>
            <param-name>contextconfiglocation</param-name>
            <param-value>classpath:springmvc.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>

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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--    扫描组件-->
    <context:component-scan base-package="com.vector"/>

    <!-- 配置thymeleaf视图解析器 -->
    <bean id="viewresolver" class="org.thymeleaf.spring5.view.thymeleafviewresolver">
        <property name="order" value="1"/>
        <property name="characterencoding" value="utf-8"/>
        <property name="templateengine">

            <bean class="org.thymeleaf.spring5.springtemplateengine">
                <property name="templateresolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.springresourcetemplateresolver">

                        <!-- 视图前缀 -->
                        <property name="prefix" value="/web-inf/templates/"/>

                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templatemode" value="html5"/>
                        <property name="characterencoding" value="utf-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!-- 处理响应中文内容乱码 -->
    <bean class="org.springframework.http.converter.stringhttpmessageconverter">
        <property name="defaultcharset" value="utf-8" />
        <property name="supportedmediatypes">
            <list>
                <value>text/html</value>
                <value>application/json</value>
            </list>
        </property>
    </bean>

    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/file" view-name="file"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <!--必须通过文件解析器的解析才能将文件转换为multipartfile对象-->
    <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"></bean>
</beans>

实现页面跳转,vue文件解析,上传内容解析的关键

SpringMVC实现文件上传下载的全过程

file.html内容demo

<body>
<a th:href="@{/testdown}" rel="external nofollow" >下载1.jpg</a>
<form th:action="@{/testup}" method="post" enctype="multipart/form-data">
    头像: <input type="file" name="photo"><br>
    <input type="submit" value="上传">
</form>
</body>

二、实现文件下载,上传功能

package com.vector.controller;

import org.springframework.beans.factory.annotation.value;
import org.springframework.http.httpheaders;
import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.stereotype.controller;
import org.springframework.util.multivaluemap;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.multipart.multipartfile;

import javax.annotation.resource;
import javax.servlet.servletcontext;
import javax.servlet.http.httpsession;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.uuid;

@controller
public class fileupanddowncontroller {

    @requestmapping("/testdown")
    public responseentity<byte[]> testresponseentity(httpsession session) throws ioexception {
        //获取servletcontext对象
        servletcontext servletcontext = session.getservletcontext();
        //获取服务器中文件的真实路径
        string realpath = servletcontext.getrealpath("/static/img/1.jpg");
        //创建输入流
        inputstream is = new fileinputstream(realpath);
        //创建字节数组
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建httpheaders对象设置响应头信息
        multivaluemap<string, string> headers = new httpheaders();
        //设置要下载方式以及下载文件的名字
        //content-disposition 固定回复内容格式  attachment以附件形式下载  filename=1.jpg文件名
        //可以将filename拼接为动态命名
        headers.add("content-disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        httpstatus statuscode = httpstatus.ok;
        //创建responseentity对象
        responseentity<byte[]> responseentity = new responseentity<>(bytes, headers, statuscode);
        //关闭输入流
        is.close();
        return responseentity;
    }
    @requestmapping("/testup")
    public string testup(@value("multipartresolver") multipartfile photo,httpsession session) throws ioexception {
        //获取上传的文件的文件名
        string filename = photo.getoriginalfilename();
        //处理文件重名问题
        //重名问题是java.io中写入同一文件默认覆盖原文件内容导致图片被覆盖.
        //获取文件名后缀
        string suffixname = filename.substring(filename.lastindexof("."));
        //将uuid作为文件名  uuid是32位随机数,几乎不可能会重复
        filename = uuid.randomuuid().tostring() + suffixname;
        //获取服务器中photo目录的路径
        servletcontext servletcontext = session.getservletcontext();
        string photopath = servletcontext.getrealpath("photo");
        file file = new file(photopath);
        //判断服务器是否存在该路径
        if(!file.exists()){
            file.mkdir();
        }
        string finalpath = photopath + file.separator + filename;
        //实现上传功能
        photo.transferto(new file(finalpath));
        return "success";
    }
}

下载功能测试

SpringMVC实现文件上传下载的全过程

SpringMVC实现文件上传下载的全过程

上传功能测试

 

SpringMVC实现文件上传下载的全过程

SpringMVC实现文件上传下载的全过程


SpringMVC实现文件上传下载的全过程

总结

到此这篇关于springmvc实现文件上传下载的文章就介绍到这了,更多相关springmvc文件上传下载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!