springboot 整合fastdfs示例

springboot 整合fastdfs

Fastdfs的下载安装请参照上一节

搭建FastDFS文件上传服务器

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>demo</artifactId>
        <groupId>com.huazhi</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>fastdfs</artifactId>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
        </dependency>

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

    </dependencies>

</project>

application.yml

fdfs:
  connect-timeout: 30  #连接超时时间
  tracker-list: 192.168.139.131:22122
  so-timeout: 30 #读取超时时间
spring:
  application:
    name: fdfs-test

server:
  port: 8080

service

package com.fastdfs.cn.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FdfsService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String upload(MultipartFile file, String fileExtName) throws Exception {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);

        return storePath.getFullPath();
    }
}

controller

package com.fastdfs.cn.controller;

import com.fastdfs.cn.service.FdfsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileContoller {
    @Autowired
    private FdfsService fdfsService;

    public String upload(MultipartFile file) {
        if (file == null) {
            return "文件为空";
        }
        String[] split = file.getOriginalFilename().split("\\.");
        String upload = null;
        try {
            upload = fdfsService.upload(file, split[split.length - 1]);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return upload;
    }
}

返回参数: test/M00/00/00/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx

打开浏览器:输入192.168.139.131:8888/test/M00/00/00/xxxxxxxxxxxxxxxxxxxxxxxxxxxxx即可访问测试。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41725792/article/details/110400402