多文件分布式上传-SpringBoot

45 篇文章 5 订阅
42 篇文章 1 订阅

前言

在现代化的互联网应用中,各种形式的上传都成为了必备的功能之一。而对于大文件上传以及多文件上传来说,我们往往需要考虑分布式储存的方案,以实现高效和可扩展性。

本文将详细介绍在SpringBoot中实现多文件分布式上传的方法,我们将使用一个开源软件FastDFS作为我们的分布式储存方案。

实现思路

在实现多文件分布式上传之前,我们需要了解一些必要的预备知识和技术:

  • FastDFS - 一款开源的轻量级分布式文件系统。
  • SpringBoot - 基于Java的轻量级Web开发框架。
  • Thymeleaf - 基于Java的模板引擎。

我们将使用SpringBoot作为我们的后端开发框架,采用Thymeleaf模板引擎作为我们的前端展示。而FastDFS则作为我们的分布式储存方案。

总体的实现思路步骤如下:

  1. 前端页面通过SpringBoot后端暴露的RESTful接口,向FastDFS服务器上传文件。
  2. 后端接收到前端上传的文件,并通过FastDFS上传至储存服务器。
  3. 后端返回文件的储存路径,以供前端进行展示。

环境准备

在进行实现之前,我们需要对环境进行一些准备。

首先,我们需要下载和安装FastDFS,在此不再赘述。其次,我们需要添加如下依赖至项目的pom.xml文件中:

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

<dependency>
	<groupId>org.csource</groupId>
	<artifactId>fastdfs-client-java</artifactId>
	<version>1.29-SNAPSHOT</version>
	<exclusions>
		<exclusion>
			<artifactId>log4j-api</artifactId>
			<groupId>org.apache.logging.log4j</groupId>
		</exclusion>
		<exclusion>
			<artifactId>log4j-core</artifactId>
			<groupId>org.apache.logging.log4j</groupId>
		</exclusion>
	</exclusions>
</dependency>

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

其中,fastdfs-client-java是FastDFS的Java客户端,spring-boot-starter-web作为SpringBoot中Web项目的起步依赖,spring-boot-starter-thymeleaf是Thymeleaf模板引擎的依赖。

为了方便管理FastDFS服务器的配置,在项目的resources目录下新建一个名为fdfs_client.conf的文件,添加如下配置:

# 连接超时时间(单位:毫秒)
connect_timeout=600
# 网络超时时间(单位:毫秒)
network_timeout=1200
# 编码字符集
charset=UTF-8
# HTTP访问服务的端口号
http.tracker_http_port=8888
# HTTP访问服务的IP地址(需要填写Tracker服务的地址)
http.tracker_http_ip=tracker:80
# Tracker服务器列表,多个tracker使用半角逗号分隔
tracker_server=tracker:22122

其中,tracker_http_iptracker_server需要根据实际情况进行配置。

实现步骤

1. 前端页面的实现

src/main/resources/templates目录下新建一个index.html文件,作为我们的前端页面,添加如下代码:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot Multiple File Upload</title>
</head>
<body>
    <form th:action="@{/upload}" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple>
        <button type="submit">Upload</button>
    </form>
</body>
</html>

在该页面中,我们向用户展示了一个用于文件选择的<input>表单和一个用于提交用户选择的文件的<button>按钮。当用户点击提交按钮时,我们将利用SpringBoot后端暴露的/upload接口向FastDFS服务器上传文件。

2. 后端接口的实现

在SpringBoot中,我们可以使用@RestController注解定义一个RESTful风格的Web服务,用于接收前端的请求。

src/main/java目录下新建一个UploadController.java文件,并添加如下代码:

package com.example.upload.controller;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.multipart.MultipartFile;

import java.io.IOException;

@Controller
public class UploadController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${fdfs.conf.path}")
    private String fdfsConfPath;

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

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("files") MultipartFile[] files, Model model) {
        try {
            // 加载FastDFS的配置文件
            ClientGlobal.init(fdfsConfPath);

            // 创建TrackerClient
            TrackerClient trackerClient = new TrackerClient();

            // 获取TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();

            // 获取StorageServer
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);

            // 创建StorageClient
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);

            String[] result = null;

            for (MultipartFile file : files) {
                // 获取文件名称
                String originalFilename = file.getOriginalFilename();

                // 获取文件扩展名
                String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

                // 执行上传
                result = storageClient.upload_file(file.getBytes(), extName, null);

                logger.info("文件上传成功,储存路径为:" + result[0] + "/" + result[1]);

                model.addAttribute("message", "文件上传成功");
                model.addAttribute("path", result[0] + "/" + result[1]);
            }
        } catch (IOException | MyException e) {
            logger.error("文件上传失败", e);

            model.addAttribute("message", "文件上传失败");
        }

        return "result";
    }
}

在上述代码中,我们使用了@Value注解注入了FastDFS的配置文件路径。在handleFileUpload方法中,我们使用FastDFS客户端进行了文件上传,并通过SpringBoot后端向前端返回了文件的储存路径。如果上传失败,则返回上传失败信息。

除此之外,我们还在index()方法中定义了访问/路径时返回的页面,并在handleFileUpload方法中定义了访问/upload路径时的上传接口。

3. 前端展示页面的实现

src/main/resources/templates目录下新建一个result.html文件,作为文件上传成功后的页面,添加如下代码:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Upload Result</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
    <p th:text="${path}"></p>
</body>
</html>

在该页面中,我们使用了Thymeleaf模板引擎的语法,动态地向用户展示上传结果,并展示了文件的储存路径。

至此,我们的多文件分布式上传功能实现完毕。

总结

本文详细介绍了如何在SpringBoot中实现多文件分布式上传,并用代码给出了相应的实现思路和实现步骤。通过本文的学习,读者可以了解到如何使用FastDFS作为分布式文件储存方案,如何在SpringBoot中搭建RESTful接口,以及如何使用Thymeleaf模板引擎进行前端展示。希望本文能够对您有所帮助!

完整代码请参考文末的GitHub链接。

参考资料

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
# 该项目骨架集成了以下技术: - SpringBoot多环境配置 - SpringMVC - Spring - MyBaits - MyBatis Generator - MyBatis PageHelper - Druid - Lombok - JWT - Spring Security - JavaMail - Thymeleaf - HttpClient - FileUpload - Spring Scheduler - Hibernate Validator - Redis Cluster - MySQL主从复制,读写分离 - Spring Async - Spring Cache - Swagger - Spring Test - MockMvc - HTTPS - Spring DevTools - Spring Actuator - Logback+Slf4j多环境日志 - i18n - Maven Multi-Module - WebSocket - ElasticSearch # 功能们: ## 用户模块 - 获取图片验证码 - 登录:解决重复登录问题 - 注册 - 分页查询用户信息 - 修改用户信息 ## 站内信模块 - 一对一发送站内信 - 管理员广播 - 读取站内信(未读和已读) - 一对多发送站内信 ## 文件模块 - 文件 - 文件下载 ## 邮件模块 - 单独发送邮件 - 群发邮件 - Thymeleaf邮件模板 ## 安全模块 - 注解形式的权限校验 - 拦截器 ## 文章管理模块 - 增改删查 # 整合注意点 1. 每个Mapper上都要加@Mapper 2. yaml文件 @Value获取xx.xx.xx不可行,必须使用@ConfigurationProperties,指定prefix,属性设置setter和getter 3. logback日志重复打印:自定义logger上加上 ` additivity="false" ` 4. SpringBoot 项目没有项目名 5. 登录 Spring Security +JWT - 已登录用户验证token - 主要是在Filter中操作。 从requestHeader中取得token,检查token的合法性,检查这一步可以解析出username去查数据库; 也可以查询缓存,如果缓存中有该token,那么就没有问题,可以放行。 - 未登录用户进行登录 - 登录时要构造UsernamePasswordAuthenticationToken,用户名和密码来自于参数,然后调用AuthenticationManager的authenticate方法, 它会去调用UserDetailsService的loadFromUsername,参数是token的username,然后比对password,检查userDetails的一些状态。 如果一切正常,那么会返回Authentication。返回的Authentication的用户名和密码是正确的用户名和密码,并且还放入了之前查询出的Roles。 调用getAuthentication然后调用getPrinciple可以得到之前听过UserDetailsService查询出的UserDetails - 在Controller中使用@PreAuthorize等注解需要在spring-web配置文件中扫描security包下的类 6. 引用application.properties中的属性的方式:@ConfigurationProperties(prefix = "spring.mail") + @Component + setter + getter 7. 引用其他自定义配置文件中的属性的方式: - @Component - ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙漠真有鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值