文件上传下载
| <dependency> |
| <groupId>commons-fileupload</groupId> |
| <artifactId>commons-fileupload</artifactId> |
| <version>1.3.1</version> |
| </dependency> |
| # 配置跳转到上传下载的页面 |
| <mvc:view-controller path="/file" view-name="file"></mvc:view-controller> |
| # http://localhost:8080/上下文路径/ file |
| |
| |
| <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> |
| <!DOCTYPE html> |
| <html lang="en" xmlns:th="http://www.thymeleaf.org"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>测试文件上传和下载</title> |
| </head> |
| <body> |
| <a th:href="@{/testDown}">下载1.jpg</a><br> |
| <form th:action="@{/testUp}" method="post" enctype="multipart/form-data"> |
| 头像:<input type="file" name="photo"><br> |
| <input type="submit" value="上传"> |
| </form> |
| </body> |
| </html> |
| @Controller |
| public class FileUpAndDownController { |
| |
| @RequestMapping("/testDown") |
| public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException { |
| |
| ServletContext servletContext = session.getServletContext(); |
| |
| String realPath = servletContext.getRealPath("/static/img/1.jpg"); |
| System.out.println(realPath); |
| |
| InputStream is = new FileInputStream(realPath); |
| |
| byte[] bytes = new byte[is.available()]; |
| |
| is.read(bytes); |
| |
| MultiValueMap<String, String> headers = new HttpHeaders(); |
| |
| headers.add("Content-Disposition", "attachment;filename=1.jpg"); |
| |
| HttpStatus statusCode = HttpStatus.OK; |
| |
| ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode); |
| |
| is.close(); |
| return responseEntity; |
| } |
| |
| @RequestMapping("/testUp") |
| public String testUp(MultipartFile photo, HttpSession session) throws IOException { |
| |
| String fileName = photo.getOriginalFilename(); |
| |
| String suffixName = fileName.substring(fileName.lastIndexOf(".")); |
| |
| String uuid = UUID.randomUUID().toString().replaceAll("-",""); |
| |
| fileName = uuid + suffixName; |
| |
| ServletContext servletContext = session.getServletContext(); |
| String photoPath = servletContext.getRealPath("photo"); |
| File file = new File(photoPath); |
| |
| if(!file.exists()){ |
| |
| file.mkdir(); |
| } |
| String finalPath = photoPath + File.separator + fileName; |
| |
| photo.transferTo(new File(finalPath)); |
| return "success"; |
| } |
| } |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?