【第15章】spring-mvc之文件上传和下载


前言

请注意,从Spring Framework 6.0及其新的Servlet 5.0+基线开始,基于Apache Commons FileUpload的过时的CommonsMultipartResolver不再可用。
本章节我们基于官方文档来进行文件的上传和下载。


一、准备

1. 打开开关(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_6_0.xsd"
         version="6.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-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config/>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2. 解析器(spring-mvc.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="org.example.springmvc"></context:component-scan>

<!--    <mvc:annotation-driven/>-->
    <!--静态资源配置-->
    <mvc:resources mapping="/**" location="/resources"></mvc:resources>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
</beans>

二、上传

1. 前端

<%--
  Created by IntelliJ IDEA.
  User: 张军国001
  Date: 2024/5/3
  Time: 10:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传和下载</title>
</head>
<body>
<h1><%= "文件上传演示" %></h1>
<br/>
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
    <span>文件:</span><input type="file" name="file">
    <button type="submit">上传</button>
</form>
</body>
</html>

2. 后端

package org.example.springmvc.params.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Create by zjg on 2024/5/3
 */
@RequestMapping("/file/")
@RestController
public class FileController {
    String path="WEB-INF/nas";
    @RequestMapping("upload")
    public void upload(@RequestPart MultipartFile file, HttpServletRequest request,HttpServletResponse response) throws IOException {
        String filename = file.getOriginalFilename();
        System.out.println(filename);
        String realPath = request.getServletContext().getRealPath(path);
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(new File(realPath+File.separator+filename));
        System.out.println(String.format("[%s]上传成功",filename));
        response.setStatus(200);
    }
}

3. 结果

[springmvc.png]上传成功

三、下载

1.前端

<%--
  Created by IntelliJ IDEA.
  User: 张军国001
  Date: 2024/5/3
  Time: 10:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传和下载</title>
</head>
<body>
<h1><%= "文件下载演示" %></h1>
<form action="${pageContext.request.contextPath}/file/download">
    <span>文件:</span><input type="text" name="file" id="file">
    <button type="submit">下载</button>
</form>
</body>
</html>

2.后端

package org.example.springmvc.params.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Create by zjg on 2024/5/3
 */
@RequestMapping("/file/")
@RestController
public class FileController {
    String path="WEB-INF/nas";
    @RequestMapping("download")
    public void download(String file,HttpServletRequest request,HttpServletResponse response) throws IOException {
        String realPath = request.getServletContext().getRealPath(path);
        String filename=realPath+File.separator+ file;
        File file1 = new File(filename);
        if(!file1.exists()){
            // 如果文件不存在,则返回404错误
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            System.out.println(String.format("文件[%s]不存在",file));
            return;
        }
        downloadFile(file1,response);
        System.out.println(String.format("[%s]下载完成",file));
        response.setStatus(200);
    }
    public void downloadFile(File file,HttpServletResponse response) throws IOException {
        // 设置响应头
        // 设置响应的内容类型为二进制流,这样浏览器就知道如何下载文件而不是尝试显示它
        response.setContentType("application/octet-stream");

        // 设置响应头中的Content-Disposition,它告诉浏览器这是一个需要下载的文件,以及下载后文件的默认名称
        // attachment表示需要下载,filename表示下载后的默认文件名
        String headerValue = "attachment; filename=\"" + file.getName() + "\"";
        response.setHeader("Content-Disposition", headerValue);

        // 设置响应头中的Content-Length,它告诉浏览器文件的大小
        response.setContentLength((int) file.length());

        // 写入文件内容到输出流
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();

        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        // 关闭流
        inputStream.close();
        outputStream.close();
    }
}

3. 结果

文件[spring]不存在
[springmvc.png]下载完成

总结

回到顶部
官方文档

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值