文章目录
- 前言
- 一、准备
- 1. 打开开关(web.xml)
- 2. 解析器(spring-mvc.xml)
- 二、上传
- 1. 前端
- 2. 后端
- 3. 结果
- 三、下载
- 1.前端
- 2.后端
- 3. 结果
- 总结
前言
请注意,从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.xsdhttp://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsdhttp://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: 张军国001Date: 2024/5/3Time: 10:32To 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: 张军国001Date: 2024/5/3Time: 10:32To 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]下载完成
总结
回到顶部
官方文档