在Spring Boot中实现文件上传与管理

在Spring Boot中实现文件上传与管理

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!

在现代应用程序中,文件上传与管理是一个常见的需求。在 Spring Boot 中,可以非常方便地实现文件上传和管理。本文将详细介绍如何在 Spring Boot 中实现文件上传功能,包括创建上传接口、文件存储、文件访问等方面的内容。我们将提供示例代码,帮助你快速实现文件上传与管理功能。

文件上传接口实现

1. 添加依赖

首先,需要在 pom.xml 中添加相关的依赖,以支持文件上传功能。Spring Boot 的 spring-boot-starter-web 已经包含了对文件上传的基本支持。

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 配置文件上传

Spring Boot 默认使用 CommonsMultipartFile 作为文件上传的对象。你可以在 application.properties 文件中配置文件上传的最大大小限制:

properties 复制代码
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3. 创建文件上传控制器

接下来,我们创建一个文件上传的控制器,处理文件上传请求。

java 复制代码
package cn.juwatech.fileupload;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FileUploadController {

    private static final String UPLOAD_DIR = "uploads/";

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "No file uploaded";
        }

        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            File destinationFile = new File(UPLOAD_DIR + file.getOriginalFilename());
            file.transferTo(destinationFile);
            return "File uploaded successfully: " + destinationFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed";
        }
    }
}

在上述代码中,我们定义了一个 FileUploadController 类,它包含一个 handleFileUpload 方法来处理文件上传。上传的文件将被保存到服务器的 uploads 目录下。

文件管理

1. 列出文件

除了上传文件,我们还需要提供一个接口来列出已上传的文件:

java 复制代码
package cn.juwatech.fileupload;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileListController {

    private static final String UPLOAD_DIR = "uploads/";

    @GetMapping("/list")
    public List<String> listFiles() {
        File folder = new File(UPLOAD_DIR);
        File[] files = folder.listFiles((dir, name) -> !name.startsWith("."));
        List<String> fileNames = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                fileNames.add(file.getName());
            }
        }
        return fileNames;
    }
}

FileListController 提供了一个 listFiles 方法,列出 uploads 目录中的所有文件。

2. 下载文件

要实现文件下载功能,我们可以创建一个控制器来处理下载请求:

java 复制代码
package cn.juwatech.fileupload;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/files")
public class FileDownloadController {

    private static final String UPLOAD_DIR = "uploads/";

    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        File file = new File(UPLOAD_DIR + filename);
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        Resource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(resource);
    }
}

FileDownloadController 提供了一个 downloadFile 方法,允许用户通过指定文件名下载文件。

3. 删除文件

为了支持文件删除操作,可以添加一个删除接口:

java 复制代码
package cn.juwatech.fileupload;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/files")
public class FileDeleteController {

    private static final String UPLOAD_DIR = "uploads/";

    @DeleteMapping("/delete/{filename:.+}")
    public String deleteFile(@PathVariable String filename) {
        File file = new File(UPLOAD_DIR + filename);
        if (file.delete()) {
            return "File deleted successfully";
        } else {
            return "File not found or delete failed";
        }
    }
}

FileDeleteController 提供了一个 deleteFile 方法,允许用户删除指定的文件。

前端页面(可选)

可以使用 Thymeleaf 或其他模板引擎来创建前端页面以支持文件上传和管理。以下是一个简单的 HTML 表单示例,用于上传文件:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h1>File Upload</h1>
    <form action="/files/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <button type="submit">Upload</button>
    </form>
</body>
</html>

这个 HTML 文件提供了一个简单的文件上传表单,用户可以选择文件并提交上传请求。

总结

在 Spring Boot 中实现文件上传与管理非常简单。通过配置文件上传、创建文件上传、下载、列表和删除接口,我们可以轻松地处理文件操作。结合前端页面,可以提供一个完整的文件管理系统。希望这些示例能帮助你实现你自己的文件管理功能。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!

相关推荐
Full Stack Developme8 分钟前
java.nio 包详解
java·python·nio
零千叶24 分钟前
【面试】Java JVM 调优面试手册
java·开发语言·jvm
代码充电宝33 分钟前
LeetCode 算法题【简单】290. 单词规律
java·算法·leetcode·职场和发展·哈希表
li37149089037 分钟前
nginx报400bad request 请求头过大异常处理
java·运维·nginx
摇滚侠41 分钟前
Spring Boot 项目, idea 控制台日志设置彩色
java·spring boot·intellij-idea
helloworddm1 小时前
Orleans 流系统握手机制时序图
后端·c#
Aevget1 小时前
「Java EE开发指南」用MyEclipse开发的EJB开发工具(二)
java·ide·java-ee·eclipse·myeclipse
黄昏晓x2 小时前
C++----多态
java·jvm·c++
Brookty2 小时前
【算法】前缀和
java·学习·算法·前缀和·动态规划
开心-开心急了2 小时前
Flask入门教程——李辉 第三章 关键知识梳理
后端·python·flask