FastDFSを用いた画像アップロードの実装

技術的背景:

FastDFSをインストールした後、プロジェクトで実際に利用することが可能です。簡単なデモを作成し、画像のアップロードを実現しました。

実装内容:

1. Spring Bootプロジェクトの構築

1.1 pom.xml 依存関係
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>cn.bestwu</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2</version>
</dependency>
1.2 application.properties 設定ファイル
# 静的リソースパス設定
spring.mvc.static-path-pattern=/static/**

# Thymeleafキャッシュ無効化(開発時のみ)
spring.thymeleaf.cache=false

# テンプレート存在チェック
spring.thymeleaf.check-template-location=true

# Content-Type設定
spring.thymeleaf.content-type=text/html

# MVC Thymeleafビュー解決有効化
spring.thymeleaf.enabled=true

# テンプレート接頭辞
spring.thymeleaf.prefix=classpath:/templates/

# テンプレート接尾辞
spring.thymeleaf.suffix=.html
1.3 各層パッケージの作成

コントローラー、エンティティ、ユーティリティなどのパッケージを作成します。

1.4 結果返却クラス `ResponseEntity` の追加
public class ResponseEntity implements Serializable {
    private boolean isSuccess;
    private String message;

    public ResponseEntity(boolean isSuccess, String message) {
        this.isSuccess = isSuccess;
        this.message = message;
    }

    // getterとsetterメソッド
}
1.5 FastDFSアップロードユーティリティクラス `FDFSUploader`
public class FDFSUploader {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageClient storageClient = null;

    public FDFSUploader(String configPath) throws Exception {
        ClientGlobal.init(configPath);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageClient = new StorageClient(trackerServer, null);
    }

    public String uploadFile(byte[] content, String extName) throws Exception {
        return storageClient.upload_file(content, extName, null);
    }
}
1.6 ImageControllerでの画像アップロード処理
@PostMapping("/upload")
@ResponseBody
public ResponseEntity upload(MultipartFile file) {
    try {
        FDFSUploader uploader = new FDFSUploader("classpath:config/fdfs_client.conf");
        String url = FILE_SERVER_URL + uploader.uploadFile(file.getBytes(), getFileExtension(file.getOriginalFilename()));
        return new ResponseEntity(true, url);
    } catch (Exception e) {
        return new ResponseEntity(false, "アップロード失敗");
    }
}

2. フロントエンドの実装

2.1 IndexControllerでindexページを返す方法
@RequestMapping(value = {"", "/"})
public String index() {
    return "index";
}
2.2 HTMLページでの画像アップロード領域のバインド
<!--画像アップロード開始-->
<div class="form-group col-md-12">
    <label>画像アップロード</label>
    <div class="form-controls">
        <li id="image_ul" style="width: 163px;height: 108px;cursor: pointer;">
            <input type="file" id="image_file" hidden>
            <a onclick="triggerUpload()" title="クリックしてアップロード"></a>
        </li>
    </div>
</div>
<!--画像アップロード終了-->
2.3 upload.js
// 画像アップロードトリガー
function triggerUpload() {
    $("#image_file").click();
}

// ファイル選択時のイベントハンドラ
$("input[type='file']").change(function(e) {
    var file = this.files[0];
    var formData = new FormData();
    formData.append("file", file);

    $.ajax({
        method: 'POST',
        url: '/upload',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.isSuccess) {
                var imgHtml = '<li><img src="' + response.message + '" /></li>';
                $("#image_ul").before(imgHtml);
            }
        },
        error: function() {
            console.log("アップロード失敗");
        }
    });
});

タグ: FastDFS SpringBoot Thymeleaf javascript jQuery

5月30日 23:24 投稿