SpringCloud集成fastdfs文件服务器

<!-- 文件服务器客户端 -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.2</version>
</dependency>

fdfs:

soTimeout: 30000

connectTimeout: 20000

thumbImage:

width: 150

height: 150

trackerList:

- 192.168.111.170:22122

这里用的是nacos配置中心 配置是yml类型

FastDFSClient 类

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
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;
import java.nio.charset.Charset;

@Component
public class FastDFSClient {

    @Autowired
    private FastFileStorageClient storageClient;


// @Autowired
// private AppConfig appConfig; // 项目参数配置

    /**
     * 上传文件
     *
     * @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.getPath();
    }

    public String uploadFile2(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);

        return storePath.getPath();
    }

    public String uploadQRCode(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                "png", null);

        return storePath.getPath();
    }

    public String uploadFace(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                "png", null);

        return storePath.getPath();
    }

    public String uploadBase64(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                "png", null);

        return storePath.getPath();
    }

    /**
     * 下载文件
     *
     * @param groupName
     * @param path
     * @param callback
     * @param <T>
     * @return
     */
    public <T> T downloadFile(String groupName, String path, DownloadCallback<T> callback) {
        T file = storageClient.downloadFile(groupName, path, callback);
        return file;
    }

    /**
     * 将一段字符串生成一个文件上传
     *
     * @param content       文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return storePath.getPath();
    }

    // 封装图片完整URL地址
// private String getResAccessUrl(StorePath storePath) {
//    String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost() + ":" + appConfig.getFdfsStoragePort()
//          + "/" + storePath.getFullPath();
//    return fileUrl;
// }

    /**
     * 删除文件
     *
     * @param fileUrl 文件访问地址
     * @return
     */
    public boolean deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return false;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            return true;
        } catch (FdfsUnsupportStorePathException e) {
            e.getMessage();
            return false;
        }
    }
}

 

FastdfsImporter类 (读取配置)
import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class FastdfsImporter {

}
UploadController 类 
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.util.FastDFSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/fastdfsUpload")
public class UploadController {
    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile multipartFile) {

        try {
            String uploadFile = fastDFSClient.uploadFile(multipartFile);
            String filename = multipartFile.getResource().getFilename();
            //下载时源文件名,回显时可以使用原文件名
            return Result.ok(uploadFile+"?filename="+filename);
        } catch (Exception ex) {
            log.info(ex.getMessage(), ex);
            return Result.error("上传失败!");
        }

    }

    /**
     * 上传头像
     * @param multipartFile
     * @return
     */
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile multipartFile) {

        try {
            String uploadFile = fastDFSClient.uploadFile(multipartFile);
            String filename = multipartFile.getResource().getFilename();
            return Result.ok(uploadFile);
        } catch (Exception ex) {
            log.info(ex.getMessage(), ex);
            return Result.error("上传失败!");
        }

    }
    /**
     * 文件删除
     *
     * @param url
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(String url) {
        boolean b = fastDFSClient.deleteFile(url);
        if (b) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * 文件下载(这里可能存在问题,没有深入,我没有用到这一块的下载)
     *
     * @param fileUrl
     * @return
     */
  /**  @PostMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] file= fastDFSClient.downloadFile(group, path, downloadByteArray );
    
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/
}

 

nginx 配置

location /group1/M00{
       alias /usr/local/fastdfs/fastdfs-5.11/storage/data; //存放图片的位置 
        if ($arg_attname ~ "^(.+)") {
            #设置下载
            add_header Content-Type application/x-download;
            #设置文件名
            add_header Content-Disposition "attachment;filename=$arg_attname";
            }
       ngx_fastdfs_module;
       }

基本上安装这样子操作下来就可以用了,这也是比较简单的,没有什么多余的代码不用去下载开源的什么项目自己打包,这个简单好用

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值