使用spring-webmvc6实现文件上传及下载

  • 使用SpringMVC6版本,不需要添加以下依赖:
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.5</version>
</dependency>
  • 新建maven模块springmvc-009,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">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>com.powernode</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmvc-009</artifactId>
    <packaging>war</packaging>


    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.1.7</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring6</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <!--指定servlet-api有tomcat容器提供,打包时将不会将servlet-api包加入打包中-->
            <scope>provided</scope>
        </dependency>

     <!--   <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>-->

<!--        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.5.3</version>
        </dependency>-->

    </dependencies>
</project>
  • 增加web支持,web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <!--字符编码过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--前端控制器-->
    <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:dispatcherServlet-servlet.xml</param-value>
        </init-param>
        <multipart-config>
            <!--支持最大文件大小-->
            <max-file-size>1024000</max-file-size>
            <!--表单中多选的所有文件上传最大值-->
            <max-request-size>1024000</max-request-size>
            <!--设置最小文件上传大小-->
            <file-size-threshold>0</file-size-threshold>
        </multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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: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.powernode.springmvc.controller"/>

    <!--视图控制器-->
    <!--视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
        <!--作用于视图渲染过程中,设置视图渲染后输出时采用的编码字符集-->
        <property name="characterEncoding" value="utf-8"/>
        <!--若存在多个视图解析器,配置优先级,值越小优先级越高-->
        <property name="order" value="1"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring6.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
                        <!--设置模板文件的位置-->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!--设置模板文件后缀-->
                        <property name="suffix" value=".html"/>
                        <!--设置模板类型-->
                        <property name="templateMode" value="HTML"/>
                        <!--设置模板文件在读取和解析过程中采用的编码字符集-->
                        <property name="characterEncoding" value="utf-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--视图控制器-->
    <mvc:view-controller path="/" view-name="index"/>

    <!--开启注解驱动-->
    <mvc:annotation-driven/>

    <!--静态资源处理-->
    <mvc:default-servlet-handler/>
</beans>
  • 配置前端首页
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传与下载</title>
</head>
<body>
<h1>文件上传与下载</h1>
<hr>
<form th:action="@{/fileup}" method="post" enctype="multipart/form-data">
    文件上传: <input type="file" name="fileName"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>
  • 配置FileController
package com.powernode.springmvc.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@RestController
public class FileController {
    @RequestMapping(value = "/fileup",method = RequestMethod.POST)
    public String fileup(@RequestParam("fileName") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String name = multipartFile.getName();
        System.out.println(name);//获取的名字是fineName
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println(originalFilename);//获取的名字是文件原名
        Path path = Paths.get(name);
        System.out.println("path:"+ path);
        //获取输入流
        InputStream inputStream = multipartFile.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        //输出流
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        File destFile = new File(file.getAbsolutePath() + "/" + UUID.randomUUID().toString() + originalFilename);


        //输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));

        //一边读一边写
        byte[] bytes = new byte[1024 * 10];
        int readCount = 0;
        while((readCount = bis.read(bytes)) != -1){
            bos.write(bytes, 0,readCount);
        }

        bos.flush();
        bos.close();
        bis.close();
        return "ok";
    }
}

最后重启tomcat,测试

成功上传到服务器指定地址:

文件下载

在index.html页面新增

<!--文件下载-->
<a th:href="@{/download/Photoshop.jpg}">文件下载</a>

在FileController类中新增

 //文件下载
    @GetMapping("/download/{filename}")
    public ResponseEntity downloadFile(@PathVariable(value = "filename")String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File(request.getServletContext().getRealPath("/upload/") + filename);
        // 创建响应头对象
        HttpHeaders headers = new HttpHeaders();
        // 设置响应内容类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 设置下载文件的名称
        headers.setContentDispositionFormData("attachment", file.getName());
//        System.out.println(file.getName());

        // 下载文件,第一种方法一次性读取下载文件,对内存有压力
        ResponseEntity entity = new ResponseEntity(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
        return entity;

        //下载文件,第一种方法二种方法,将之前创建的InputStreamResource对象(在这里是resource)设置到响应体中。
        /*InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);*/
    }

重启tomcat,打开浏览器点击"文件下载"

补充:
.headers(headers): 这将之前创建的HttpHeaders对象(在这里是headers)设置到响应头中。这个headers对象应该包含必要的响应头信息,例如Content-Type(指定文件类型)和Content-Disposition(指定文件名为附件,以便浏览器提示用户下载而不是尝试打开它)。

posted @ 2024-07-12 23:53  文采杰出  阅读(270)  评论(0)    收藏  举报