Spring+SpringMVC+Tomcat实现上传文件和下载文件

相关准备

配置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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>syr</groupId>
    <artifactId>UploadDownload</artifactId>
    <version>1.0</version>
    <name>UploadDownload</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.9.2</junit.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.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.33</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.33</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.15.1</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</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>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-config.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

配置spring-config.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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 开启Tomcat默认Servlet的功能 -->
    <mvc:default-servlet-handler/>
    <!-- 开启注解扫描 -->
    <mvc:annotation-driven/>
    <!-- 开启包扫描 -->
    <context:component-scan base-package="syr.controller"/>
    <!-- 将上传文件的数据(复杂表单数据)解析成一个MultipartFile对象,后端可以通过这个对象获取文件相关信息 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 将上传文件的最大尺寸设置为1MB -->
        <property name="maxUploadSize" value="1048576"/>
    </bean>
</beans>

创建index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/upload.jsp">上传文件</a>
<a href="${pageContext.request.contextPath}/download.jsp">下载文件</a>
</body>
</html>

上传文件

前端代码

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>上传文件</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
<a href="${pageContext.request.contextPath}/index.jsp">返回首页</a>
</body>
</html>

后端代码

package syr.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Objects;
import java.util.UUID;

@Controller
public class UploadController {
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //如果上传的文件为空,回到上传文件页面
        if (file.isEmpty()) {
            return "redirect:/upload.jsp";
        }
        //获取上传的真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        //获取文件的扩展名
        String extension = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //使用UUID作为前缀名,防止名字重复被覆盖
        String fileName = UUID.randomUUID() + extension;
        //获取输入流
        InputStream inputStream = file.getInputStream();
        //获取输出流
        OutputStream outputStream = Files.newOutputStream(new File(realPath, fileName).toPath());
        //实现文件复制
        IOUtils.copy(inputStream, outputStream);
        //关闭输入流
        IOUtils.closeQuietly(inputStream);
        //关闭输出流
        IOUtils.closeQuietly(outputStream);
        //回到上传页面
        return "redirect:/upload.jsp";
    }
}

下载文件

前端代码

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>下载文件</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/download?fileName=头像.png">头像.png</a>
<a href="${pageContext.request.contextPath}/index.jsp">返回首页</a>
</body>
</html>

后端代码

package syr.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

@Controller
public class DownloadController {
    @RequestMapping("/download")
    public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取文件在服务器上的绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        //获取输入流
        InputStream inputStream = Files.newInputStream(new File(realPath, fileName).toPath());
        //解决中文名称文件下载异常的问题
        if (request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")) {
            //IE浏览器
            fileName = URLEncoder.encode(fileName, "utf-8");
        } else if (request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            //Edge浏览器
            fileName = URLEncoder.encode(fileName, "utf-8");
        } else {
            //其它浏览器
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        //设置文件下载的名字,避免浏览器在线预览文件
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        //获取输出流
        OutputStream outputStream = response.getOutputStream();
        //实现文件下载
        IOUtils.copy(inputStream, outputStream);
        //关闭输入流
        IOUtils.closeQuietly(inputStream);
        //关闭输出流
        IOUtils.closeQuietly(outputStream);
        //回到下载页面
        return "redirect:/download.jsp";
    }
}
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花园宝宝没有天线

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值