如何在Spring MVC中实现图片的上传和下载功能

简介: 如何在Spring MVC中实现图片的上传和下载功能

Spring MVC 是一个用于构建基于Java的Web应用的框架,它提供了一个易于使用的开发环境来创建复杂的Web应用。本文将详细介绍如何在Spring MVC中实现图片的上传和下载功能。

 

一、环境准备

 

1. **创建Spring MVC项目**:

   - 使用Spring Initializr生成一个基础的Spring Boot项目,选择`Web`依赖项。

   - 添加Maven依赖:

 

```xml
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      ```

 

2. **配置文件**:

   - 在`application.properties`文件中添加以下配置:

 

```properties
      spring.servlet.multipart.enabled=true
      spring.servlet.multipart.max-file-size=2MB
      spring.servlet.multipart.max-request-size=2MB
      ```

 

二、图片上传功能

 

1. **创建上传表单**:

   - 在`src/main/resources/templates`目录下创建`upload.html`文件,内容如下:

 

```html
      <!DOCTYPE html>
      <html xmlns:th="http://www.thymeleaf.org">
      <head>
          <title>Upload Image</title>
      </head>
      <body>
          <h1>Upload Image</h1>
          <form method="POST" enctype="multipart/form-data" th:action="@{/upload}">
              <input type="file" name="file" accept="image/*"/>
              <button type="submit">Upload</button>
          </form>
      </body>
      </html>
      ```

 

2. **创建Controller**:

   - 在`src/main/java/com/example/demo/controller`目录下创建`UploadController.java`文件,内容如下:

```java
      package com.example.demo.controller;
 
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.Model;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PostMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.multipart.MultipartFile;
 
      import java.io.File;
      import java.io.IOException;
      import java.nio.file.Path;
      import java.nio.file.Paths;
 
      @Controller
      public class UploadController {
 
          private static final String UPLOAD_DIR = "uploads/";
 
          @GetMapping("/upload")
          public String uploadForm() {
              return "upload";
          }
 
          @PostMapping("/upload")
          public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
              if (file.isEmpty()) {
                  model.addAttribute("message", "Please select a file to upload.");
                  return "upload";
              }
 
              try {
                  // 获取文件名
                  String fileName = file.getOriginalFilename();
                  // 设置保存路径
                  Path path = Paths.get(UPLOAD_DIR + fileName);
                  // 保存文件到服务器
                  file.transferTo(path.toFile());
 
                  model.addAttribute("message", "File uploaded successfully: " + fileName);
              } catch (IOException e) {
                  model.addAttribute("message", "Failed to upload file: " + e.getMessage());
              }
 
              return "upload";
          }
      }
      ```

 

3. **创建保存目录**:

   - 在项目根目录下创建一个`uploads`文件夹,用于存放上传的图片。

 

三、图片下载功能

 

1. **创建下载表单**:

   - 在`src/main/resources/templates`目录下创建`download.html`文件,内容如下:

```html
      <!DOCTYPE html>
      <html xmlns:th="http://www.thymeleaf.org">
      <head>
          <title>Download Image</title>
      </head>
      <body>
          <h1>Download Image</h1>
          <form method="GET" th:action="@{/download}">
              <input type="text" name="filename" placeholder="Enter filename"/>
              <button type="submit">Download</button>
          </form>
      </body>
      </html>
      ```

 

2. **更新Controller**:

   - 在`UploadController.java`文件中添加下载功能的代码:

```java
      import org.springframework.core.io.FileSystemResource;
      import org.springframework.core.io.Resource;
      import org.springframework.http.HttpHeaders;
      import org.springframework.http.ResponseEntity;
      import org.springframework.web.bind.annotation.RequestParam;
 
      @GetMapping("/download")
      public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) {
          File file = new File(UPLOAD_DIR + filename);
          if (!file.exists()) {
              return ResponseEntity.notFound().build();
          }
 
          Resource resource = new FileSystemResource(file);
          return ResponseEntity.ok()
              .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
              .body(resource);
      }
      ```

 

四、测试功能

 

1. **启动项目**:

   - 运行Spring Boot项目,启动Web服务器。

 

2. **上传图片**:

   - 在浏览器中访问`http://localhost:8080/upload`,选择图片文件并点击上传按钮。

 

3. **下载图片**:

   - 在浏览器中访问`http://localhost:8080/download`,输入上传的文件名并点击下载按钮。

 

通过以上步骤,我们成功实现了Spring MVC中图片的上传和下载功能。

 

 

五、完善上传和下载功能

 

1. **改进上传功能**:

 

  - 在上传时,避免文件名冲突,可以添加时间戳或UUID。

  - 对上传文件进行类型检查,只允许图片格式。

 

  修改后的`UploadController.java`如下:

```java
   import org.springframework.util.StringUtils;
 
   @PostMapping("/upload")
   public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
       if (file.isEmpty()) {
           model.addAttribute("message", "Please select a file to upload.");
           return "upload";
       }
 
       try {
           // 获取文件名,并添加时间戳避免冲突
           String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
           String fileName = System.currentTimeMillis() + "_" + originalFileName;
 
           // 检查文件类型
           String fileType = file.getContentType();
           if (fileType == null || !fileType.startsWith("image")) {
               model.addAttribute("message", "Only image files are allowed.");
               return "upload";
           }
 
           // 设置保存路径
           Path path = Paths.get(UPLOAD_DIR + fileName);
           // 保存文件到服务器
           file.transferTo(path.toFile());
 
           model.addAttribute("message", "File uploaded successfully: " + fileName);
       } catch (IOException e) {
           model.addAttribute("message", "Failed to upload file: " + e.getMessage());
       }
 
       return "upload";
   }
   ```

 

2. **改进下载功能**:

 

  - 提供下载文件列表,避免手动输入文件名。

  - 增加文件不存在时的友好提示。

 

  修改后的`UploadController.java`如下:

 

```java
   import java.util.stream.Collectors;
   import java.util.stream.Stream;
 
   @GetMapping("/download")
   public String downloadForm(Model model) {
       File folder = new File(UPLOAD_DIR);
       String[] files = folder.list();
       if (files != null) {
           model.addAttribute("files", Stream.of(files).collect(Collectors.toList()));
       } else {
           model.addAttribute("files", new ArrayList<>());
       }
       return "download";
   }
 
   @GetMapping("/download/{filename}")
   public ResponseEntity<Resource> downloadFile(@PathVariable("filename") String filename) {
       File file = new File(UPLOAD_DIR + filename);
       if (!file.exists()) {
           return ResponseEntity.notFound().build();
       }
 
       Resource resource = new FileSystemResource(file);
       return ResponseEntity.ok()
           .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
           .body(resource);
   }
   ```

 

  同时修改`download.html`,如下:

 

```html
   <!DOCTYPE html>
   <html xmlns:th="http://www.thymeleaf.org">
   <head>
       <title>Download Image</title>
   </head>
   <body>
       <h1>Download Image</h1>
       <ul>
           <li th:each="file : ${files}">
               <a th:href="@{/download/{filename}(filename=${file})}" th:text="${file}">Filename</a>
           </li>
       </ul>
   </body>
   </html>
   ```

 

六、文件大小限制与异常处理

 

1. **文件大小限制**:

 

  - 配置文件大小限制,防止上传过大的文件影响服务器性能。

 

  在`application.properties`文件中添加:

```properties
   spring.servlet.multipart.max-file-size=5MB
   spring.servlet.multipart.max-request-size=5MB
   ```

 

2. **异常处理**:

 

  - 创建全局异常处理器来处理文件上传相关的异常。

 

  在`src/main/java/com/example/demo/exception`目录下创建`GlobalExceptionHandler.java`文件:

```java
   package com.example.demo.exception;
 
   import org.springframework.web.bind.annotation.ControllerAdvice;
   import org.springframework.web.bind.annotation.ExceptionHandler;
   import org.springframework.web.multipart.MaxUploadSizeExceededException;
   import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
   @ControllerAdvice
   public class GlobalExceptionHandler {
 
       @ExceptionHandler(MaxUploadSizeExceededException.class)
       public String handleMaxSizeException(MaxUploadSizeExceededException exc, RedirectAttributes redirectAttributes) {
           redirectAttributes.addFlashAttribute("message", "File too large!");
           return "redirect:/upload";
       }
   }
   ```

 

七、项目结构总结

 

项目结构如下:

```
src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── controller
│   │               │   └── UploadController.java
│   │               └── exception
│   │                   └── GlobalExceptionHandler.java
│   ├── resources
│   │   └── templates
│   │       ├── upload.html
│   │       └── download.html
│   └── application.properties
└── test
```

 

通过以上步骤,你已经成功实现了Spring MVC中图片的上传和下载功能,并且处理了文件大小限制和异常情况。

 

八、测试上传和下载功能

 

1. **启动项目**:

   - 运行Spring Boot项目,启动Web服务器。

 

2. **上传图片**:

   - 在浏览器中访问`http://localhost:8080/upload`,选择图片文件并点击上传按钮。

 

3. **下载图片**:

   - 在浏览器中访问`http://localhost:8080/download`,点击文件名链接下载图片。

 

 

相关文章
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
936 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
10月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
1632 0
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
1010 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
972 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
624 0
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
873 0
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
381 0
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
460 0
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
1028 29