三、springboot操作fastDFS

一、导包

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

二、在application.yml,引入配置文件

# 分布式文件系统FDFS配置
fdfs:
  soTimeout: 1500 #socket连接超时时长
  connectTimeout: 600 #连接tracker服务器超时时长
  resHost: 46.116.114.122 #请求访问入口,如果作集群,可以是虚拟api
  resPort: 80 #storagePort,以nginx,http方式上传与下载
  thumbImage: #缩略图生成参数,可选
    width: 150
    height: 150
  tracker-list: #TrackerList参数,支持多个,如果有多个在下方加- x.x.x.x:port
    - 46.113.116.122:22122

 

三、初始化配置

@Component
public class AppConfig {
    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.resPort}")
    private String resPort;

    public String getResHost() {
        return resHost;
    }

    public void setResHost(String resHost) {
        this.resHost = resHost;
    }

    public String getResPort() {
        return resPort;
    }

    public void setResPort(String resPort) {
        this.resPort = resPort;
    }
}

 

@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {

}

 

四、封装操作工具

@Component
public class FastDFSClientUitl {

    @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 getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public String uploadStrToFile(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 getResAccessUrl(storePath);
    }

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

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

        }
    }

    /**
     * 文件下载
     * @param path
     * @return
     */
    public void downLoad(@RequestParam String group,
                         @RequestParam String path,
                         @RequestParam String fileName,
                         HttpServletResponse response) throws IOException {

        // 获取文件
        // 例:storageClient.download_file("group1", "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg");
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());

        //设置相应类型application/octet-stream
        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();
    }
}

 

五、访问

@RestController
@RequestMapping("/fastDFS")
public class FastDFSController {

    @Autowired
    FastDFSClientUitl fastDFSClientUitl;

    @PostMapping("/upload")
    public ScgResponse upload(@RequestParam("file") MultipartFile file) throws Exception {
        String imgUrl = fastDFSClientUitl.uploadFile(file);
        System.out.println("fastDFS上传文件返回的url:"+imgUrl);
        return ScgResponse.ok().put("url",imgUrl);
    }


}

 

posted @ 2020-03-05 10:40  柠檬仔啊  阅读(545)  评论(0)    收藏  举报