SpringBoot 开发案例之整合FastDFS分布式文件系统

1、pom依赖

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

2、application.properties

server.port=8082
#超时时长 fdfs.so
-timeout=1500 #连接tracker服务器超时时长 fdfs.connect-timeout=600 #缩略图 fdfs.thumb-image.height=150 fdfs.thumb-image.width=150 #tracker服务配置地址列表,替换成自己服务的IP地址,支持多个 fdfs.tracker-list=192.168.206.173:22122 #文件上传配置 spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=20MB

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 例如: group1/M00/00/00/wKjOrWD45PKAY4xmAFLQaGXPnu0735.jpg
     */
    public void delete(String path)
    {
        fastFileStorageClient.deleteFile(path);
    }

    /**
     * 删除
     *
     * @param group 例如: group1
     * @param path  例如: M00/00/00/wKjOrWD45PKAY4xmAFLQaGXPnu0735.jpg
     */
    public void delete(String group, String path)
    {
        fastFileStorageClient.deleteFile(group, path);
    }

    /**
     * 文件下载
     *
     * @param path     文件路径,例如:group1/M00/00/00/wKjOrWD40JiAQNKLABO5RCqSdcQ975.jpg
     * @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());
        }
        else
        {
            filename = filename + storePath.getPath().substring(storePath.getPath().lastIndexOf("."));
        }
        byte[] bytes =
            fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }
}

4、controller层代码

@RestController
public class FileController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FastdfsUtils fastdfsUtils;

    @PostMapping("uploadFile")
    private StorePath uploadFile(MultipartFile file)
    {
        StorePath storePath = null;
        try
        {
            storePath = fastdfsUtils.upload(file);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.info("服务异常");
        }
        return storePath;
    }

    @PostMapping("deleteByPath")
    private String deleteByPath(String path)
    {
        try
        {
            fastdfsUtils.delete(path);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.info("删除异常");
        }
        return "success";
    }

    @GetMapping("downloadFile")
    private void downloadFile(String path, String name, HttpServletResponse response)
    {
        try
        {
            fastdfsUtils.download(path, name, response);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.info("下载异常");
        }
    }
}
原文地址:https://www.cnblogs.com/qq1445496485/p/15043345.html