ITPub博客

首页 > 数据库 > 数据库开发技术 > 今日代码大赏 | 本地文件存储

今日代码大赏 | 本地文件存储

原创 数据库开发技术 作者:程序员鱼皮 时间:2024-04-22 14:33:56 0 删除 编辑

在如今的 Web 应用开发中,文件的上传是一个常见的需求。用户上传头像、文件等,需要一个稳定且易于使用的文件处理机制。虽然如今各种云厂商提供了对象存储服务,但是对于我们初学者来说,还是想要一种无需成本的本地文件存储方法。

今天,我们就来深入了解如何在 SpringBoot 中实现本地文件存储功能。示例代码如下:

import org.springframework.core.io.Resource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
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;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;

@RestController
public class FileUploadController {

    private static final Logger log = Logger.getLogger(FileUploadController.class.getName());
    private static final Path UPLOAD_DIR = Paths.get("uploads"); // 设置文件上传的目录

    @PostMapping("/upload")
    public ResponseEntity<Result<String>> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Result.error("文件为空,上传失败"));
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 确保上传目录存在
            Files.createDirectories(UPLOAD_DIR);
            
            // 保存文件到服务器的指定目录
            Path targetLocation = UPLOAD_DIR.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 返回成功的响应
            return ResponseEntity.ok(Result.success("文件上传成功,文件名:" + fileName));
        } catch (IOException e) {
            log.severe("文件上传失败:" + e.getMessage());
            return ResponseEntity.status(500).body(Result.error("文件上传失败,服务器内部错误"));
        }
    }
}

今天的文件上传功能是建立在定义一个 Result 类上,如果你想完整实现文件上传功能,可以参考之前我们分享的 SpringBoot 创建统一结果返回类。可以点击下方文字,直接跳转原文哦!

今日代码大赏 | 统一结果返回类

今天的代码大赏就到这里了。希望通过这篇文章,你能够对在 SpringBoot 中实现本地文件存储功能有一个更深入的理解。

完整代码片段来源于代码小抄,欢迎点击进入小程序阅读!

在线访问:https://www.codecopy.cn/post/wmlc1f

在代码小抄可以看到更多优质代码,也欢迎大家积极分享,可能会获得我们官方的小礼品 🎁~

往期推荐

这个 404 页面,是真的炫酷~

我成功复刻了安卓 6 的彩蛋!

今日代码大赏 | Python 实现归并排序算法

今日代码大赏 | Java 实现二分查找算法

今日代码大赏 | 统一结果返回类

原文作者:程序员鱼皮;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2023-12-20

  • 博文量
    330
  • 访问量
    151696