如何在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`,点击文件名链接下载图片。

 

 

相关文章
|
4月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
567 2
|
9月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
311 32
|
9月前
|
安全 Java API
Spring Boot 功能模块全解析:构建现代Java应用的技术图谱
Spring Boot不是一个单一的工具,而是一个由众多功能模块组成的生态系统。这些模块可以根据应用需求灵活组合,构建从简单的REST API到复杂的微服务系统,再到现代的AI驱动应用。
1185 8
|
8月前
|
监控 安全 Java
Java 开发中基于 Spring Boot 3.2 框架集成 MQTT 5.0 协议实现消息推送与订阅功能的技术方案解析
本文介绍基于Spring Boot 3.2集成MQTT 5.0的消息推送与订阅技术方案,涵盖核心技术栈选型(Spring Boot、Eclipse Paho、HiveMQ)、项目搭建与配置、消息发布与订阅服务实现,以及在智能家居控制系统中的应用实例。同时,详细探讨了安全增强(TLS/SSL)、性能优化(异步处理与背压控制)、测试监控及生产环境部署方案,为构建高可用、高性能的消息通信系统提供全面指导。附资源下载链接:[https://pan.quark.cn/s/14fcf913bae6](https://pan.quark.cn/s/14fcf913bae6)。
1718 0
|
10月前
|
SQL 前端开发 Java
深入理解 Spring Boot 项目中的分页与排序功能
本文深入讲解了在Spring Boot项目中实现分页与排序功能的完整流程。通过实际案例,从Service层接口设计到Mapper层SQL动态生成,再到Controller层参数传递及前端页面交互,逐一剖析每个环节的核心逻辑与实现细节。重点包括分页计算、排序参数校验、动态SQL处理以及前后端联动,确保数据展示高效且安全。适合希望掌握分页排序实现原理的开发者参考学习。
678 4
|
设计模式 XML Java
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
本文详细介绍了Spring框架的核心功能,并通过手写自定义Spring框架的方式,深入理解了Spring的IOC(控制反转)和DI(依赖注入)功能,并且学会实际运用设计模式到真实开发中。
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
|
监控 前端开发 API
一款基于 .NET MVC 框架开发、功能全面的MES系统
一款基于 .NET MVC 框架开发、功能全面的MES系统
503 5
|
XML Java 数据格式
Spring Core核心类库的功能与应用实践分析
【12月更文挑战第1天】大家好,今天我们来聊聊Spring Core这个强大的核心类库。Spring Core作为Spring框架的基础,提供了控制反转(IOC)和依赖注入(DI)等核心功能,以及企业级功能,如JNDI和定时任务等。通过本文,我们将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring Core,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
197 14