一、pom中加入依赖
<!--fastdfs文件上传-->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.3</version>
</dependency>
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
二、编写配置类
1.配置文件
fdfs:
# 读取时间
soTimeout: 1501
# 连接超时时间
connectTimeout: 601
# 编码默认UTF-8,charset属性不能自定义
# charset: UTF-8
# 缩略图
thumbImage:
# 宽
width: 150
# 高
height: 150
# tracker列表
trackerList:
- ${serverIp}:22122
pool:
max-total: 50
max-wait-millis: 500
web-server-url: ${serverIp}
2.配置类
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)// 解决jmx重复注册bean的问题
public class FastDFSConfiguration {
}
三、编写工具类
import com.github.tobato.fastdfs.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
/**fastdfs文件上传工具类
* @Author kexianjun
* @Data 2019/9/17 11:02
* @Description
* @Project parent
* @Package com.yncjtz.util
* @Since JDK1.8
*/
@Component
public class FastDFSClient {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
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.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
e.getMessage();
}
}
}
文件上传和下载案列
1.文件上传
/**
* 文件上传
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/upload/file")
@ResponseBody
public Map<String,Object> upload(@RequestParam("file") MultipartFile file, Model model) throws Exception{
Map<String,Object> resultMap = new HashMap<>();
String url = null;
try {
url = fdfsClient.uploadFile(file);
resultMap.put("code", 200);
resultMap.put("message", "上传成功");
resultMap.put("url", url);
System.out.println(url);
} catch (Exception e) {
resultMap.put("status", 500);
resultMap.put("message", "上传异常!");
}
return resultMap;
}
2.文件下载
/**
* 文件下载
* @param fileUrl url 开头从组名开始
* @param response
* @throws Exception
*/
@RequestMapping(value="/download", method = {RequestMethod.GET})
public void download(HttpServletResponse response, HttpServletRequest request) throws Exception{
String fileUrl = request.getParameter("fileUrl");
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);
}