SpringMVC文件上传与下载

环境的搭建

用idea创建java Enterprise项目,手动添加Tomcat。

在resources目录下创建Spring的配置文件。

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解配置-->
    <context:component-scan base-package="xin.students"/>

    <context:annotation-config/>

    <!--开启注Aspect生成代理对象-->
    <aop:aspectj-autoproxy/>

    <!--开启mvc注解配置-->
    <mvc:annotation-driven/>

    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/imgs/**" location="/imgs/"/>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--上传文件的最大大小-->
    <property name="maxUploadSizePerFile" value="20140000"/>

    <!--缓存大小-->
    <property name="maxInMemorySize" value="102400"/>

    <!--文件编码-->
    <property name="defaultEncoding" value="utf-8"/>

</bean>

</beans>

maven依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>xin.students</groupId>
    <artifactId>SpringMVC-File-down-update</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>SpringMVC-File-down-update</name>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <junit.version>5.7.1</junit.version>
        <spring-version>5.3.16</spring-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <!--spring-mvc的JSON转换工具依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.1</version>
            </plugin>
        </plugins>
    </build>
</project>

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

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>

    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--设置编码器的编码-->
        <init-param>
            <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>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

index.jsp文件

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>

<table width="100%" height="700px">
    <td width="200px" style="border-right: deepskyblue 2px solid; background-color: rgba(255,0,0,0.1)">
        <ul>
            <li><a href="book-add.jsp" target="mainFrame">添加图书</a></li

            <li><a href="#">图书列表</a></li>
            <li><a href="tisp.jsp" target="mainFrame">图书列表</a></li>
        </ul>
    </td>
    <td>
        <iframe name="mainFrame" width="100%" height="700px" frameborder="2px"></iframe>
    </td>

</table>

</body>
</html>

book-add.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>

<h4>添加图书信息</h4>
<form action="/book/add" method="post" enctype="multipart/form-data">
    <p>图书名称:<input type="text" name="bookName"></p>
    <p>图书作者:<input type="text" name="bookAuthor"></p>
    <p>图书价格:<input type="text" name="bookPrice"></p>
    <p>图书明面:<input type="file" name="imgFile"></p>
    <p><input type="submit" value="提交"></p>
</form>

</body>
</html>

Book.java

package xin.students.beans;

public class Book {
    private Integer bookId;
    private String bookName;
    private String bookAuthor;
    private Double bookPrice;
    private String bookImg;

    public Book() {
    }

    public Book(Integer bookId, String bookName, String bookAuthor, Double bookPrice, String bookImg) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
        this.bookPrice = bookPrice;
        this.bookImg = bookImg;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    public Double getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(Double bookPrice) {
        this.bookPrice = bookPrice;
    }

    public String getBookImg() {
        return bookImg;
    }

    public void setBookImg(String bookImg) {
        this.bookImg = bookImg;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", bookAuthor='" + bookAuthor + '\'' +
                ", bookPrice=" + bookPrice +
                ", bookImg='" + bookImg + '\'' +
                '}';
    }
}

文件的上传

前端上传文件

<h4>添加图书信息</h4>
<form action="/book/add" method="post" enctype="multipart/form-data">
    <p>图书名称:<input type="text" name="bookName"></p>
    <p>图书作者:<input type="text" name="bookAuthor"></p>
    <p>图书价格:<input type="text" name="bookPrice"></p>
    <p>图书明面:<input type="file" name="imgFile"></p>
    <p><input type="submit" value="提交"></p>
</form>

控制器接收数据和文件

SpringMVC处理上传文件需要借助CommonsMultipartResolver文件解析器

添加依赖:commons-io commons-fileupload

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

在spring-servlet.xml中配置文件解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--上传文件的最大大小-->
    <property name="maxUploadSizePerFile" value="20140000"/>

    <!--缓存大小-->
    <property name="maxInMemorySize" value="102400"/>

    <!--文件编码-->
    <property name="defaultEncoding" value="utf-8"/>

    <!--接收到的文件存储位置-->
    <property name="uploadTempDir" value="C:\\Users\\Administrator\\Desktop\\"/>
</bean>

控制器接收文件

在处理文件上传的方法中定义一个MultPartFile类型的对象,就可以接收图片了。

@Controller
@RequestMapping("/book")
public class BookController {
    @RequestMapping("/add")
    public String addBook(Book book, MultipartFile imgFile, HttpServletRequest request) throws IOException {

        //获取文件名
        String originalFilename = imgFile.getOriginalFilename();

        //截取文件的后缀名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        //获取imgs目录在服务器中的绝对路径
        String dir = request.getServletContext().getRealPath("imgs");

        //获取当前毫秒值生成文件名
        String fileName = System.currentTimeMillis() + ext;

        //设置文件的绝对路径
        String savePath = dir + "/" + fileName;

        //写入到指定路径
        imgFile.transferTo(new File(savePath));

        return "/tisp.jsp";
    }
}

文件的下载

前端代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件列表</title>
    <script src="js/jquery-3.6.0.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
          integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
            crossorigin="anonymous"></script>
</head>

<style>
    img {
        height: 70%;
        margin-right: 50px;
    }
</style>

<script>
    $(function () {
        $.get("/book/list", function (res) {
            for (let i = 0, len = res.length; i < len; i++) {
                let imgName = res[i];
                let htmlStr = "<div class='col-lg-2 col-md-4 col-sm-6'><div class='thumbnail'><img src='imgs/" + imgName + "' alt=''><div class='caption'><p><a href='book/download?fileName=" + imgName + "' class='btn btn-primary' role='button'>Download</a></p></div></div></div>"
                $("#container").append(htmlStr);
            }
        })
    }, "json");
</script>

<body>
<h1>图片列表</h1>
<div class="row" id="container">

</div>
</body>
</html>

后盾代码

@Controller
@RequestMapping("/book")
public class BookController {
    @RequestMapping("/list")
    @ResponseBody
    public String[] listImages(HttpServletRequest request) {
        //获取目录信息
        String dir = request.getServletContext().getRealPath("imgs");
        File imgDir = new File(dir);
        //返回文件夹下的所有文件名
        String[] file = imgDir.list();
        return file;
    }

    @RequestMapping("/download")
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String dirPath = request.getServletContext().getRealPath("imgs");
        String filePath = dirPath + "/" + fileName;
        FileInputStream fileInputStream = new FileInputStream(filePath);

        //设置相应的文件类型,类型要写成浏览器不能显示的,可以随便写
        response.setContentType("application/exe");

        //设置相应头和要保存的文件名
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        //org.apache.commons.io.IOUtils包下的,把文件流返回给用户流
        IOUtils.copy(fileInputStream, response.getOutputStream());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值