spring boot实现图片上传和下载功能

yizhihongxing

下面我将针对“spring boot实现图片上传和下载功能”的完整操作过程进行详细讲解,并提供两个示例以供参考。

准备工作

在开始实现图片上传和下载功能之前,我们需要先准备好开发环境和所需要的依赖。具体流程如下:

环境搭建

  • JDK 1.8及以上版本
  • Maven 3.2及以上版本
  • IDE开发工具(如Eclipse、IntelliJ IDEA等)

需要依赖

在Maven项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.3.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.3.9.RELEASE</version>
</dependency>

同时,为了让程序能够上传和下载文件,还需要引入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.3.9.RELEASE</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.4</version>
</dependency>

实现图片上传和下载功能

实现图片上传

  1. 创建上传文件的Controller类,并添加上传文件页面。
@Controller
public class FileUploadController {

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
        FileUtils.writeByteArrayToFile(new File("D://" + file.getOriginalFilename()), file.getBytes());
        model.addAttribute("msg", "File uploaded successfully");
        return "upload_status";
    }
}

其中,/是上传文件的页面路径,upload是上传文件的页面名称,/upload是上传文件的处理路径,upload_status是处理上传结果的页面名称。

  1. 创建上传页面upload.html。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>File Upload</title>
</head>
<body>
<div>
    <form method="POST" enctype="multipart/form-data" th:action="@{/upload}">
        <input type="file" name="file" />
        <button type="submit">Submit</button>
    </form>
</div>
</body>
</html>
  1. 创建上传结果页面upload_status.html。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>File Upload Status</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>

实现图片下载

  1. 创建实体类File。
@Entity
public class File {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String path;

    private String type;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
  1. 创建文件上传和下载服务类FileService。
@Service
public class FileService {

    @Autowired
    private FileRepository fileRepository;

    public void upload(MultipartFile file) throws Exception {
        String path = "D://";
        String name = file.getOriginalFilename();
        File f = new File();
        f.setName(name);
        f.setPath(path);
        f.setType(file.getContentType());
        FileUtils.writeByteArrayToFile(new File(path + name), file.getBytes());
        fileRepository.save(f);
    }

    public ResponseEntity<Resource> download(Long id) throws Exception {
        Optional<File> optional = fileRepository.findById(id);
        if (optional.isPresent()) {
            File f = optional.get();
            InputStreamResource resource = new InputStreamResource(new FileInputStream(new File(f.getPath() + f.getName())));
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, f.getType())
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + f.getName() + "\"")
                    .body(resource);
        }
        throw new Exception("File not found.");
    }
}

其中,FileRepository是用于声明和操作实体类File的数据库操作类。

  1. 创建上传文件处理器和下载文件处理器。
@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> download(@PathVariable Long id) throws Exception {
        return fileService.download(id);
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) throws Exception {
        fileService.upload(file);
        model.addAttribute("msg", "File uploaded successfully");
        return "upload_status";
    }
}

其中,/download/{id}是下载文件的处理路径,/upload是上传文件的处理路径。

  1. 创建下载文件页面download.html。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>File Download</title>
</head>
<body>
<div>
    <h1>File Download</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Action</th>
        </tr>
        <tr th:each="file : ${files}">
            <td th:text="${file.id}"></td>
            <td th:text="${file.name}"></td>
            <td><a th:href="@{/download/{id}(id=${file.id})}">Download</a></td>
        </tr>
    </table>
</div>
</body>
</html>

总结

通过以上步骤,我们已经成功实现了基于Spring Boot框架的图片上传和下载功能。在实际应用中,我们可以根据自己的需求进行相应的定制和优化。同时,对于初学者而言,以上代码可以作为一个基础模板,供大家参考和学习。

示例代码1:https://github.com/ljw104925/spring-boot-file-upload-download

示例代码2:https://github.com/whvcse/FileUpDown-SpringBoot

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:spring boot实现图片上传和下载功能 - Python技术站

(0)
上一篇 2023年5月28日
下一篇 2023年5月28日

相关文章

  • 使用webpack手动搭建vue项目的步骤

    使用webpack手动搭建vue项目的步骤可能有点繁琐,但却是从根本上了解vue和webpack的运行机制、优化和调试的重要一步。 以下是手动搭建vue项目的完整攻略: 步骤1:新建项目 首先,我们需要在本地新建一个项目文件夹并打开命令行,使用npm初始化项目: npm init 这将在项目文件夹中创建一个package.json文件,其中包含了我们需要的依…

    Vue 2023年5月28日
    00
  • typescript在vue中的入门案例代码demo

    下面是关于“TypeScript在Vue中的入门案例代码demo”的完整攻略: 什么是TypeScript TypeScript是一个开源的编程语言,它是JavaScript的超集,具有类型和对象导向特性,开发者可以使用它来开发大型的Web应用或Node.js应用。它的语法看起来像JavaScript,但是针对开发体验和代码维护性做了很多改进。 如何在Vue…

    Vue 2023年5月27日
    00
  • 你要的Vue面试题都在这里

    针对“你要的Vue面试题都在这里”的完整攻略,我将从以下几个方面进行说明: 项目介绍 如何使用 示例说明 1. 项目介绍 该项目是一份Vue面试题的集锦。主要是收集了一些常见的Vue面试题,涵盖了Vue基础、Vue组件、Vue实践等各个方面。通过该项目,可以帮助大家更好的了解Vue,提升自己的Vue技能。 2. 如何使用 该项目是一个Github仓库,可以通…

    Vue 2023年5月28日
    00
  • vue js秒转天数小时分钟秒的实例代码

    下面我将详细讲解“vue js秒转天数小时分钟秒的实例代码”的完整攻略。 1. 实现思路 我们需要先将输入的秒数转换为天数、小时、分钟和秒数,然后将它们展示在页面上。具体的实现思路如下: 在Vue实例中定义一个data属性,来存储输入的秒数以及转换后的天、时、分、秒。 在计算属性中编写相应的转换方法,将秒数转换为天数、小时数、分钟数和余下的秒数。 通过Vue…

    Vue 2023年5月29日
    00
  • Vue的Props实例配置详解

    Vue的Props实例配置详解 在Vue中,Props是父组件向子组件传递数据的一个重要机制,用于解决组件之间的通信问题。本篇文章将详细讲解Vue中的Props实例配置,希望能对Vue的开发者提供帮助。 什么是Props Props是Vue中一个重要的特性,它是父组件向子组件传递数据的一个机制。可以将Props看作是父组件向子组件传递数据的一个桥梁。 如何定…

    Vue 2023年5月27日
    00
  • vue3使用vue-router的完整步骤记录

    下面就是“Vue3使用Vue Router的完整步骤记录”的攻略。 使用Vue Router包 要使用Vue Router,首先需要安装vue-router包。可以使用npm安装,命令如下所示: npm install vue-router@next 创建路由实例 Vue Router的创建需要在Vue实例之前,因为Vue Router的实例也要在Vue实例…

    Vue 2023年5月27日
    00
  • Vue 解决在element中使用$notify在提示信息中换行问题

    要在 element-ui 的 $notify 中进行换行,可以使用 html 标签进行内容换行。但是,直接在 $notify 中插入 html 标签会将其解析为字符串,而不是渲染成为 html 元素。因此许多人会通过使用 dangerouslyUseHTMLString 属性,来将 <br> 等 html 标签渲染为真正的 html 元素。 以…

    Vue 2023年5月27日
    00
  • mpvue构建小程序的方法(步骤+地址)

    mpvue是一款基于Vue.js框架的小程序前端开发框架,它可以实现在小程序中使用Vue.js的语法和开发方式,极大地提高了小程序的开发效率和代码质量。下面我将详细讲解如何使用mpvue构建小程序。 步骤 安装mpvue脚手架工具 npm install -g vue-cli vue init mpvue/mpvue-quickstart my-projec…

    Vue 2023年5月27日
    00
合作推广
合作推广
分享本页
返回顶部