Spring MVC 文件上传下载
在http://mvnrepository.com/中搜索需要的包
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"> <modelVersion>4.0.0</modelVersion> <groupId>org.mythsky</groupId> <artifactId>springmvcdemo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> </dependencies> </project>
registerForm.jsp

<%-- Created by IntelliJ IDEA. User: mythsky Date: 2017/11/21 Time: 22:31 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>注册</title> </head> <body> <h3>注册页面</h3> <form action="register" method="post"> <table> <tr> <td><label>登录名:</label></td> <td><input type="text" id="loginname" name="loginname"></td> </tr> <tr> <td><label>生日:</label></td> <td><input type="text" id="birthday" name="birthday"></td> </tr> <tr><td><input type="submit" value="登录"></td></tr> </table> </form> </body> </html>
FileUploadController

package org.mythsky.springmvcdemo.controller; 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.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; @Controller public class FileUploadController { @RequestMapping(value = "/upload",method = RequestMethod.POST) public String upload(HttpServletRequest request, @RequestParam("description") String description, @RequestParam("file")MultipartFile file)throws Exception{ System.out.println(description); if(!file.isEmpty()){ String path=request.getServletContext().getRealPath("/images/"); String filename=file.getOriginalFilename(); File filepath=new File(path,filename); if(!filepath.getParentFile().exists()){ filepath.getParentFile().mkdirs(); } file.transferTo(new File(path+File.separator+filename)); return "success"; }else{ return "error"; } } }
虽然在maven中添加了引用,可是我本机运行的时候还是报没有找到包的错误,所以把这两个包下载下来放到lib目录中
运行tomcat
上传后可以找到上传文件放到了images目录下
修改上传下载功能
User

package org.mythsky.springmvcdemo.model; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.multipart.MultipartFile; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private String loginname; private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private Date birthday; private MultipartFile image; public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } public User() { super(); } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
reguserForm.jsp

<%-- Created by IntelliJ IDEA. User: mythsky Date: 2017/12/5 Time: 21:12 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>用户注册</title> </head> <body> <h2>用户注册</h2> <form action="/reguser" enctype="multipart/form-data" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>请上传头像:</td> <td><input type="file" name="image"></td> </tr> <tr> <td><input type="submit" value="注册"></td> </tr> </table> </form> </body> </html>
userInfo.jsp

<%-- Created by IntelliJ IDEA. User: mythsky Date: 2017/12/5 Time: 21:15 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件下载</title> </head> <body> <h3>文件下载</h3> <a href="download?filename=${requestScope.user.image.originalFilename}">${requestScope.user.image.originalFilename}</a> </body> </html>
FileUploadController

@RequestMapping(value = "/reguser") public String register(HttpServletRequest request, @ModelAttribute User user, Model model)throws Exception{ System.out.println(user.getUsername()); if(!user.getImage().isEmpty()){ String path=request.getServletContext().getRealPath("/images/"); String filename=user.getImage().getOriginalFilename(); File filepath=new File(path,filename); if(!filepath.getParentFile().exists()){ filepath.getParentFile().mkdirs(); } user.getImage().transferTo(new File(path+File.separator+filename)); model.addAttribute("user",user); return "userInfo"; }else{ return "error"; } } @RequestMapping(value = "/download") public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename")String filename,Model model)throws Exception{ String path=request.getServletContext().getRealPath("/images/"); File file=new File(path+File.separator+filename); HttpHeaders headers=new HttpHeaders(); String downloadFileName=new String(filename.getBytes("UTF-8"),"iso-8859-1"); headers.setContentDispositionFormData("attachment",downloadFileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED); }
上传页面
下载页面
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!