FastDFSClient.java 2.19 KB
Newer Older
牟邦恺 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
package com.hikcreate.service.fdfs;


import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author 赵东
 * @create 2019/3/22 16:32
 */
@Component
public class FastDFSClient {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath();
    }
    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(byte[] file, String fileName) throws IOException {
        StorePath storePath = storageClient.uploadFile(new ByteArrayInputStream(file), file.length, FilenameUtils.getExtension(fileName), null);
        return storePath.getFullPath();
    }
    /**
     * 封装图片完整URL地址
     *
     * @param storePath
     * @return
     * @link https://blog.csdn.net/ityqing/article/details/81384740
     */
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }

    public byte[] download(String fileUrl) {
        int idx = fileUrl.indexOf("/", 1);
        String group = fileUrl.substring(1, idx);
        String path = fileUrl.substring(idx + 1);
        return storageClient.downloadFile(group, path, new DownloadByteArray());
    }
李辅翼 committed
65 66 67 68 69 70 71 72 73
    /**
     * 删除数据
     *
     * @param path
     * @throws IOException
     */
    public void deleteFile(String path) {
        storageClient.deleteFile(path);
    }
牟邦恺 committed
74
}