一、pom引入
<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.27.2</version> <exclusions> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency>二、application.yml的配置
# 文件系统FDFS配置 fdfs: so-timeout: 15000 connect-timeout: 15000 pool: max-total: 200 # 每个tracker地址的最大连接数 max-total-per-key: 100 # 连接耗尽时等待获取连接的最大毫秒数 max-wait-millis: 5000 thumb-image: #缩略图生成参数 width: 200 height: 200 web-server-url: www.xxx.com/ #注意‘/‘要加上,此处和返回的资源地址进行拼接 tracker-list: xx.xxx.xxx.xx:22122 # 注意开放相关端口和通信断开权限二、FastDFSClient.java
import com.alibaba.druid.util.StringUtils; import com.github.tobato.fastdfs.domain.conn.FdfsWebServer; import com.github.tobato.fastdfs.domain.fdfs.StorePath; import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray; import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException; import com.github.tobato.fastdfs.service.FastFileStorageClient; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; /** * @author :cw * @date :Created in 2020/6/1 下午5:20 * @description:fdfs注入 * @modified By: * @version: 0.0.1$ */ @Component public class FastDFSClient { private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class); @Resource private FastFileStorageClient storageClient; @Resource private FdfsWebServer fdfsWebServer; /** * 上传文件 * @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 file 文件对象 * @return 文件访问地址 * @throws IOException */ public String uploadFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream (file); StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null); return getResAccessUrl(storePath); } /** * 将一段字符串生成一个文件上传 * @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 getResAccessUrl(storePath); } // 封装图片完整URL地址 private String getResAccessUrl(StorePath storePath) { String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath(); return fileUrl; } /** * 下载文件 * @param fileUrl 文件url * @return */ public byte[] download(String fileUrl) { String group = fileUrl.substring(0, fileUrl.indexOf("/")); String path = fileUrl.substring(fileUrl.indexOf("/") + 1); byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray()); return bytes; } /** * 删除文件 * @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) { logger.warn(e.getMessage()); } } }三、创建Controller
import com.xxx.xxx.config.FastDFSClient; import com.xxx.xxx.generic.Result; import com.xxx.xxx.util.ResultUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * @author :cw * @date :Created in 2020/6/2 上午9:28 * @description:fastController封装 * @modified By: * @version: 0.0.1$ */ @RestController @RequestMapping("/fdfs") @RefreshScope @Api(tags = "用户userInfo相关接口", description = "提供用户相关的 Rest API") public class FastDFSController { @Resource private FastDFSClient fdfsClient; /** * 文件上传 * @param file * @return * @throws Exception */ @PostMapping("/upload") @ApiOperation("上传图片文件") public Result upload(MultipartFile file) throws Exception{ String url = fdfsClient.uploadFile(file); return ResultUtil.CustomResultParam(true,200,url); } /** * 文件下载 * @param fileUrl url 开头从组名开始 * @param response * @throws Exception */ @GetMapping("/download") @ApiOperation("下载图片文件") public void download(String fileUrl, HttpServletResponse response) throws Exception{ byte[] data = fdfsClient.download(fileUrl); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8")); // 写出 ServletOutputStream outputStream = response.getOutputStream(); IOUtils.write(data, outputStream); } }补充:一般上传成功后将图片返回的url地址保存在当前业务环境下 docker快速搭建单机版fastDfs资源服务器