SpringBoot アクセス FastDFS (ツールクラスを使用)

FastDFSとは何ですか?

FastDFS是用C语言编写的一款开源的轻量级分布式文件系统。它对文件进行管理,功能包括:文件存
储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合
以文件为载体的在线服务,如相册网站、视频网站等等。
FastDFS为互联网量身定制,充分考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性
能等指标,使用FastDFS很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务。

FastDFS の機能

ファイル管理システムFastDFSの詳細説明

  • グループ化されたストレージ、柔軟、簡潔、ピアツーピア構造、シングルポイントファイルなし、ブロックストレージなし、アップロードされたファイルは OS ファイルシステム内のファイルと 1 対 1 に対応します
  • ファイル ID は、ファイル アクセス資格情報として FastDFS によって生成されます。FastDFS は従来のネーム サーバーを必要とせず、一般的な Web サーバーとシームレスに接続します。FastDFS は、Apache および nginx 拡張モジュールを提供しています。
  • 中ファイルと小さなファイルの両方を適切にサポートでき、大量の小さなファイルの保存もサポートします。
  • 複数のディスクと単一ディスクのデータ復旧をサポート
  • 同じコンテンツを持つファイルのコピーを 1 つだけ保存することをサポートし、ディスク領域を節約します
  • オンライン拡張とマスター/スレーブ ファイルをサポート
  • ファイル属性 (メタデータ) をストレージ サーバーに保存できます V2.0 のネットワーク通信は、大規模な同時アクセスをサポートし、全体的なパフォーマンスが向上する libevent を使用します。
  • ファイルのダウンロードはマルチスレッドをサポートし、ブレークポイントでダウンロードを再開します。

fastDfsdocker インストール チュートリアル
fastDfs の完全なソース コード

1.jar 依存関係を導入する

        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.6</version>
        </dependency>

2.application.ymlの設定

server:
  port: 10086

# 分布式文件系统FDFS配置
fdfs:
  connect-timeout: 600  # 连接超时时间
  so-timeout: 1500      # 读取超时时间
  tracker-list: 127.0.0.1:22122  # tracker服务配置地址列表,替换成自己服务的IP地址,支持多个
  pool:
    jmx-enabled: false
  thumb-image:
    height: 150       # 缩略图的宽高
    width: 150

3. アップロードおよびダウンロード ツール

@Component
public class FastdfsUtils {
    
    

    public static final String DEFAULT_CHARSET = "UTF-8";

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 上传文件并返回文件路径
     *
     * @param file
     * @return 文件路径
     * @throws IOException
     */
    public StorePath upload(MultipartFile file) throws IOException {
    
    
        // 设置文件信息
        Set<MetaData> mataData = new HashSet<>();
        mataData.add(new MetaData("author", "fastdfs"));
        mataData.add(new MetaData("description", file.getOriginalFilename()));
        // 上传
        StorePath storePath = fastFileStorageClient.uploadFile(
                file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()),
                null);
        return storePath;
    }

    /**
     * 根据全路径删除
     *
     * @param path "fullPath": "group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg"
     */
    public void delete(String path) {
    
    
        fastFileStorageClient.deleteFile(path);
    }

    /**
     * 根据组和路径删除
     * "group": "group1",
     * "path": "M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg",
     * "fullPath": "group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg"
     *
     * @param group
     * @param path
     */
    public void delete(String group, String path) {
    
    
        fastFileStorageClient.deleteFile(group, path);
    }

    /**
     * 文件下载
     *
     * @param path     文件路径,例如:/group1/path=M00/00/00/itstyle.png
     * @param filename 下载的文件命名
     * @return
     */
    public void download(String path, String filename, HttpServletResponse response) throws IOException {
    
    
        // 获取文件
        StorePath storePath = StorePath.parseFromUrl(path);
        if (StringUtils.isBlank(filename)) {
    
    
            filename = FilenameUtils.getName(storePath.getPath());
        }
        byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, DEFAULT_CHARSET));
        response.setCharacterEncoding(DEFAULT_CHARSET);
        // 设置强制下载不打开
//        response.setContentType("application/force-download");
        ServletOutputStream outputStream = null;
        try {
    
    
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

4.コントローラークラス

/**
 * @author xlwang55
 * @date 2022/3/2 13:47
 */
@RestController
@RequestMapping("/fastdfsUtils")
public class FastDFSUtilsController {
    
    
    @Autowired
    private FastdfsUtils fastdfsUtils;

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
    
    
        StorePath storePath = fastdfsUtils.upload(file);
        String fullPath = storePath.getFullPath();
        System.out.println("fullPath = " + fullPath);
        //group1/M00/00/00/wKgAkGIfF2KAG7qSAAB-jaFjG-Q678.jpg
        return fullPath;
    }

    @GetMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response)
            throws IOException {
    
    
        fastdfsUtils.download(fileUrl, null, response);
    }

    @DeleteMapping("/delete")
    public void delete(String fileUrl) {
    
    
        fastdfsUtils.delete(fileUrl);
    }
}

5. テストに postman を使用する

5.1 アップロード

http://localhost:10086/fastdfsUtils/upload

ここに画像の説明を挿入します
ここに画像の説明を挿入します

5.2 ダウンロード

http://localhost:10086/fastdfsUtils/download

ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/weixin_43811057/article/details/123231136#comments_28960344