SpringBoot整合FastDFS实现文件的上传、下载和删除

SpringBoot整合FastDFS实现文件的上传、下载和删除

前期准备

具体准备跟Java实现实现文件的上传、下载和删除一样

可以看这里参考https://blog.csdn.net/qq_45334037/article/details/117931295?spm=1001.2014.3001.5501

具体实现

  1. 新建一个springboot工程在pom.xml导入的jar包,这个fastdfs包是自己打包的
		<!-- fastdfs -->
        <dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27-SNAPSHOT</version>
        </dependency>
        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.46</version>
        </dependency>

  1. 在resources文件下新建fastdfs.conf文件并编写
tracker_server=服务器地址:22122 //表示tracker的地址和端口如果是集群有多个就继续往下写
  1. application.yml文件的配置
server:
  port: 9999
spring:
  thymeleaf:
    cache: false
    mode: HTML
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://服务器地址:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: 数据库用户名
    password: 数据库密码
    
mybatis:
  type-aliases-package: com.yuwen.pojo
  configuration:
    map-underscore-to-camel-case: true
  1. Student实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    private String id; //学生id

    private String name; //学生姓名
 
    private String workName; //作业名称

    private String groupName; //上传后的组名

    private String remoteFilePath; //上传后的路径

    private long fileSize; //上传的文件大小
 
    private String fileOldName; //上传的文件名

}
  • StudentService接口
public interface StudentService {

    //查询所有信息
    List<Student> findAll();

    //修改学生信息
    void updateStudent(Student student);

    //根据id查询信息
    Student findStuById(String id);

    //删除信息
    void deleteById(String id);
}
  • StudentServiceImpl类
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    StudentMapper studentMapper;
    //查询所有信息
    @Override
    public List<Student> findAll() {
        return studentMapper.findAll();
    }
    //修改信息 增加文件信息
    @Override
    public void updateStudent(Student student) {
        studentMapper.updateStudent(student);
    }
    //根据id查询信息
    @Override
    public Student findStuById(String id) {
        return studentMapper.findStuById(id);
    }
    //删除文件信息
    @Override
    public void deleteById(String id) {
        Student student = studentMapper.findStuById(id);
        FastDFSUtil.delete(student.getGroupName(),student.getRemoteFilePath());
        student.setGroupName("");
        student.setRemoteFilePath("");
        student.setFileSize(0L);
        student.setFileOldName("");
        studentMapper.updateStudent(student);
    }
}
  • ServiceController类
@Controller
public class StudentController {
    @Resource
    StudentService studentService;
    @GetMapping("/")
    public String findAll(Model model){
        List<Student> studentList = studentService.findAll();
        model.addAttribute("studentList",studentList);
        return "index";
    }
    @GetMapping("/upload/{id}")
    public String toUpload(@PathVariable String id, Model model){
        Student student = studentService.findStuById(id);
        model.addAttribute("student",student);
        return "upload";
    }
    //上传文件
    @PostMapping("/upload")
    public String upload(String id, MultipartFile myFile,Model model) throws IOException {
        //获取文件字节数组
        byte[] bufferFile = myFile.getBytes();
        //获取文件名
        String fileName = myFile.getOriginalFilename();
        //获取文件大小
        Long fileSize = myFile.getSize();
        //获取文件后缀名
        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
        String[] result = FastDFSUtil.upload(bufferFile, fileExtName);
        Student student = studentService.findStuById(id);
        student.setGroupName(result[0]);
        student.setRemoteFilePath(result[1]);
        student.setFileSize(fileSize);
        student.setFileOldName(fileName);
        studentService.updateStudent(student);
        model.addAttribute("msg","上传成功");
        return "redirect:/";
    }
    /**
     * 完成文件下载
     * @param id  需要下载的文件主键
     * @return ResponseEntity 表示一个响应的实体,这个类是Spring提供的一个类,这个类是Spring响应数据时的一个对象
     *         这个对象用包含则响应时的编码例如404 200 等等,以及响应的头文件信息,以及响应时的具体数据
     *         这个数据可以是一段html代码,也可以是一段js,也可以是一段普通字符串,也可以是一个文件的流
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> download(@PathVariable String id){
        Student student = studentService.findStuById(id);
        byte [] bytes=FastDFSUtil.download(student.getGroupName(),student.getRemoteFilePath());
        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置响应类型为文件类型
        headers.setContentLength(student.getFileSize());//设置响应时的文件大小用于自动提供下载进度
        //设置下载时的默认文件名
        headers.setContentDispositionFormData("attachment",student.getFileOldName());
        /**
         * 创建响应实体对象,Spring会将这个对象返回给浏览器,作为响应数据
         * 参数 1 为响应时的具体数据
         * 参数 2 为响应时的头文件信息
         * 参数 3 为响应时的状态码
         */
        ResponseEntity<byte[]> responseEntity=new ResponseEntity<byte[]>(bytes,headers, HttpStatus.OK);
        return responseEntity;
    }
    //删除文件
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        studentService.deleteById(id);
        return "redirect:/";
    }
}
  • FastDFSUtils工具类的编写,主要操作
public class FastDFSUtil {
    /**
     * 文件上传
     */
    public static String [] upload(byte[] buffFile,String fileExtName) {
        TrackerServer ts=null;
        StorageServer ss=null;
        try {
            //读取FastDFS的配置文件用于将所有的tracker的地址读取到内存中
            ClientGlobal.init("fastdfs.conf");
            TrackerClient tc=new TrackerClient();
            ts=tc.getConnection();
            ss=tc.getStoreStorage(ts);
            //定义Storage的客户端对象,需要使用这个对象来完成具体的文件上传 下载和删除操作
            StorageClient sc=new StorageClient(ts,ss);
            /**
             * 文件上传
             * 参数 1 为需要上传的文件的字节数组
             * 参数 2 为需要上传的文件的扩展名
             * 参数 3 为文件的属性文件通常不上传
             * 返回一个String数组 这个数据对我们非常总要必须妥善保管建议存入数据库
             * 数组中的第一个元素为文件所在的组名
             * 数组中的第二个元素为文件所在远程路径名
             */
            String[] result= sc.upload_file(buffFile,fileExtName,null);

            return result;
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ts!=null){
                try {
                    ts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 下载文件
     */
    public static byte [] download(String groupName,String remoteFilename) {
        TrackerServer ts=null;
        StorageServer ss=null;
        try {
            //读取FastDFS的配置文件用于将所有的tracker的地址读取到内存中
            ClientGlobal.init("fastdfs.conf");
            TrackerClient tc=new TrackerClient();
            ts=tc.getConnection();
            ss=tc.getStoreStorage(ts);
            //定义Storage的客户端对象,需要使用这个对象来完成具体的文件上传 下载和删除操作
            StorageClient sc=new StorageClient(ts,ss);
            /**
             * 文件下载
             * 参数1 需要下载的文件的组名
             * 参数2 需要下载文件的远程文件名
             * 返回一个int类型的数据 返回0 表示文件下载成功其它值表示文件在下载失败
             */

            byte [] buffFile=sc.download_file(groupName,remoteFilename);
            return buffFile;
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ts!=null){
                try {
                    ts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 文件删除
     */
    public static void delete(String groupName,String remoteFilename) {
        TrackerServer ts=null;
        StorageServer ss=null;
        try {
            //读取FastDFS的配置文件用于将所有的tracker的地址读取到内存中
            ClientGlobal.init("fastdfs.conf");
            TrackerClient tc=new TrackerClient();
            ts=tc.getConnection();
            ss=tc.getStoreStorage(ts);
            //定义Storage的客户端对象,需要使用这个对象来完成具体的文件上传 下载和删除操作
            StorageClient sc=new StorageClient(ts,ss);
            /**
             * 文件删除
             * 参数1 需要删除的文件的组名
             * 参数2 需要删除文件的远程文件名
             * 返回一个int类型的数据 返回0 表示文件删除成功其它值表示文件在删除失败
             */
            int result=sc.delete_file(groupName,remoteFilename);
            System.out.println(result);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ts!=null){
                try {
                    ts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • StudentMapper接口
@Mapper
@Repository
public interface StudentMapper {
    //查询所有信息
    @Select("select * from student")
    List<Student> findAll();

    //修改信息
    @Update("update student set group_name=#{groupName},remote_file_path=#{remoteFilePath},file_size=#{fileSize},file_old_name=#{fileOldName} where id=#{id}")
    void updateStudent(Student student);

    //根据id查询信息
    @Select("select * from student where id = #{id}")
    Student findStuById(String id);
}

html网页

  • index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table>
    <tr>
        <td>id</td>
        <td>姓名</td>
        <td>作业名</td>
        <td>操作</td>
    </tr>
    <tr th:each="student:${studentList}">
        <td th:text="${student.getId()}">id</td>
        <td th:text="${student.getName()}">姓名</td>
        <td th:text="${student.getWorkName()}">作业名</td>
        <td>
               <span th:if="${student.remoteFilePath==null||student.remoteFilePath==''}">
                   <a th:href="@{|/upload/${student.id}|}">上传</a>
               </span>
            <span th:if="${student.remoteFilePath!=null&&student.remoteFilePath!=''}">
                   <a th:href="@{|/download/${student.id}|}">下载</a>
                   <a th:href="@{|/delete/${student.id}|}">删除</a>
               </span>
        </td>
    </tr>
</table>
</body>
</html>
  • upload.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <!--上传文件的表单 method必须为post   必须指定enctype属性为multipart/form-data  -->
   <form th:action="@{/upload}" target="success" method="post" enctype="multipart/form-data">
       姓名:<span th:text="${student.name}"></span><br>
       作业名:<span th:text="${student.workName}"></span><br>
       文件:<input type="file" name="myFile"><br>
       <input type="hidden" name="id" th:value="${student.id}">
       <input type="submit" value="上传文件">
   </form>
</body>
</html>

测试

测试上传

未上传
上传
数据库显示
上传成功
上传成功
数据库显示
数据库显示
通过数据库中的组名和文件存储路径查看文件
外部查看

测试下载

下载

测试删除

页面显示
数据库显示
数据库显示

源码地址:https://gitee.com/residual-temperature/fastdfs-springboot-demo

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一些关于如何将Spring Boot与FastDFS集成的一般步骤。以下是大致步骤: 1. 添加FastDFS客户端依赖 在您的Spring Boot项目的pom.xml文件中添加FastDFS客户端依赖,例如: ```xml <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.27.1</version> </dependency> ``` 2. 配置FastDFS客户端 在您的Spring Boot项目的application.properties或application.yml文件中添加FastDFS客户端的配置,例如: ```properties fdfs.trackerList=tracker_server1_ip:tracker_server1_port,tracker_server2_ip:tracker_server2_port ``` 3. 配置文件服务 创建一个文件服务类,例如: ```java @Service public class FileUploadService { @Autowired private FastFileStorageClient fastFileStorageClient; public String uploadFile(MultipartFile file) throws IOException { StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getFullPath(); } } ``` 4. 使用文件服务 在您的Spring Boot项目的控制器中使用文件服务,例如: ```java @RestController public class FileUploadController { @Autowired private FileUploadService fileUploadService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { return fileUploadService.uploadFile(file); } } ``` 这是一个基本的Spring Boot与FastDFS集成的示例,您可以根据您的需求进行修改和定制。希望这可以帮助到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值