- 使用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> |
| |
| <scope>provided</scope> |
| </dependency> |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| </dependencies> |
| </project> |
| <?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> |
| 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); |
| 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()); |
| |
| |
| |
| ResponseEntity entity = new ResponseEntity(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK); |
| return entity; |
| |
| |
| |
| |
| |
| |
| } |
重启tomcat,打开浏览器点击"文件下载"

补充:
.headers(headers): 这将之前创建的HttpHeaders对象(在这里是headers)设置到响应头中。这个headers对象应该包含必要的响应头信息,例如Content-Type(指定文件类型)和Content-Disposition(指定文件名为附件,以便浏览器提示用户下载而不是尝试打开它)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?