springboot2.x整合fastDfs

如果需要自己搭建文件服务器请移步:fastDfs安装配置教程

springboot整合fastDfs

  • pom.xml添加配置
        <!-- 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配置
project:
    ## 文件服务器域名
    fastDfsUrl: http://39.96.46.193/
fdfs:
  #链接超时
  connect-timeout: 2000
  # 读取时间
  so-timeout: 2000
  thumb-image:  #生成缩略图参数
    width: 150
    height: 150
  tracker-list: 39.96.46.193:22122
  • fastdfs配置类
package com.hanergy.out.config;

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)
// Jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class DfsConfig {
}
  • fastDfs工具类
package com.hanergy.out.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;


@Component
@PropertySource("classpath:application.yml")
public class FileDfsUtils {

    private static final Logger log = LoggerFactory.getLogger(FileDfsUtils.class);

    @Value("${project.fastDfsUrl}")
    private String fastDfsUrl;

    @Autowired
    private FastFileStorageClient storageClient ;
    /**
     * 上传图片 会自动裁剪(这里文件不是图片会报异常)
     */
    public String uploadImage(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
        return fastDfsUrl + storePath.getFullPath() ;
    }

    /**
     * 上传文件(通用)
     */
    public String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadFile( multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
//                uploadImageAndCrtThumbImage(
//                multipartFile.getInputStream(),
//                multipartFile.getSize(),originalFilename , null);
        return fastDfsUrl + storePath.getFullPath() ;
    }
    /**
     * @Description: 根据文件路径下载文件
     * @param filePath 文件路径
     * @return 文件字节数据
     * @throws Exception byte[]
     */
    public byte[] downFile(String filePath) throws Exception {
        StorePath storePath = StorePath.parseFromUrl(filePath);

        return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadCallback<byte[]>() {
            @Override
            public byte[] recv(InputStream ins) throws IOException {
                return IOUtils.toByteArray(ins);
            }
        });
    }

    /**
     * 删除文件
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.info("fileUrl == >>文件路径为空...");
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}

  • controller代码
package com.hanergy.out.controller;

import com.hanergy.out.utils.FileDfsUtils;
import com.hanergy.out.utils.R;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileManageController {

    @Autowired
    private FileDfsUtils fileDfsUtils;



    /**
     * 文件上传
     */
    @ApiOperation(value="上传文件", notes="测试FastDFS文件上传")
    @PostMapping(value = "/uploadFile",headers="content-type=multipart/form-data")
    public R uploadFile (@RequestParam("file") MultipartFile file){
        String result ;
        try{
            String path = fileDfsUtils.upload(file);
            if (!StringUtils.isEmpty(path)){
                result = path ;
            } else {
                result = "上传失败" ;
            }
        } catch (Exception e){
            e.printStackTrace() ;
            result = "服务异常" ;
        }
        return R.ok(1,result);
    }

    @GetMapping("/download")
    public void downFile(@RequestParam("url") String url,HttpServletResponse response) throws Exception {
        byte[] bytes = fileDfsUtils.downFile(url);
        //设置相应类型application/octet-stream        (注:applicatoin/octet-stream 为通用,一些其它的类型苹果浏览器下载内容可能为空)
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("123.png", "UTF-8"));
        // 写入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();

    }
}

至此 开发完成,可以用postman调用接口测试文件上传了

你可能感兴趣的:(代码文档)