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

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

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

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

文件上传接口实现

1. 添加依赖

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

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

2. 配置文件上传

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

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3. 创建文件上传控制器

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

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. 列出文件

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

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. 下载文件

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

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. 删除文件

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

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 表单示例,用于上传文件:

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

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

  • 18
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值