IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringMVC文件上传与下载 -> 正文阅读

[Java知识库]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());
    }
}

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-04-24 09:15:04  更:2022-04-24 09:19:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 2:51:49-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码