源码地址: https://github.com/Lijun54321/fastdfs-test
这里就不介绍了这个步骤了
<dependency>
<groupId>com.github.tobatogroupId>
<artifactId>fastdfs-clientartifactId>
<version>1.26.7version>
dependency>
启动类上直接加就行了,没必要去写一个配置类
package com.test.fastdfs;
import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
/**
* EnableMBeanExport 解决Jmx重复注册bean的问题
*
* @author 16634
*/
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class FastdfsApplication {
public static void main(String[] args) {
SpringApplication.run(FastdfsApplication.class, args);
}
}
我这是yml 文件,如果需要些properties文件的话,可以自己转换下(btw:idea 有yml转pro pro转yml 插件哟)
spring:
servlet:
multipart:
# 开启文件上传功能
enabled: true
max-file-size: 100MB
max-request-size: 100MB
# fastDFS 配置
fdfs:
# 连接超时
connect-timeout: 60
# 读取时间
so-timeout: 15000
# 生成缩略图参数
thumb-image:
width: 150
height: 150
# 支持配置多个
tracker-list:
- 192.168.1.1:22122
- ip1:port
- ip2:port
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8"/>
<title>fileUpload pagetitle>
head>
<body>
<h1 th:inlines="text">文件上传h1>
<form action="/upload1" method="post" enctype="multipart/form-data">
<p>
选择文件: <input type="file" name="file"/>
p>
<p>
<input type="submit" value="提交"/>
p>
form>
body>
html>
btw 这只是测试的,一般我们正常开发的时候,做好异常捕捉操作哦!
package com.test.fastdfs.utils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sun.deploy.association.utility.AppConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* Class Name FastDfsUtils ...
*
* @author LiJun
* Created on 2019/10/31 13:55
*/
@Component
@Slf4j
public class FastDfsUtils {
@Autowired
private FastFileStorageClient fastFileStorageClient;
/**
* 文件上传, byte 流类型
*
* @param bytes 文件字节
* @param fileSize 文件大小
* @param extension 文件扩展名
* @return fastDfs路径
*/
public String uploadFile(byte[] bytes, long fileSize, String extension) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, null);
System.out.println(storePath.getGroup() + "===" + storePath.getPath() + "======" + storePath.getFullPath());
return storePath.getFullPath();
}
/**
* MultipartFile类型的文件上传ַ
*
* @param file
* @return
* @throws IOException
*/
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = fastFileStorageClient.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 path = fastFileStorageClient.uploadFile(inputStream, file.length(),
FilenameUtils.getExtension(file.getName()), null);
return getResAccessUrl(path);
}
/**
* 带输入流形式的文件上传
*
* @param inputStream
* @param size
* @param fileName
* @return
*/
public String uploadFile(InputStream inputStream, long size, String fileName) {
StorePath path = fastFileStorageClient.uploadFile(inputStream, size, fileName, null);
return getResAccessUrl(path);
}
/**
* 将一段文本文件写到fastdfs的服务器上
*
* @param content
* @param fileExtension
* @return
*/
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath path = fastFileStorageClient.uploadFile(stream, buff.length, fileExtension, null);
return getResAccessUrl(path);
}
/**
* 下载文件
*
* @param fileUrl 文件URL
* @return 文件字节
*/
public byte[] downloadFile(String fileUrl) {
String group = fileUrl.substring(0, fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
DownloadByteArray downloadByteArray = new DownloadByteArray();
return fastFileStorageClient.downloadFile(group, path, downloadByteArray);
}
public void deleteFile(String fileUrl) {
if (StringUtils.isBlank(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (Exception e) {
log.error("", e);
}
}
/**
* 封装文件完整URL地址
*/
private String getResAccessUrl(StorePath storePath) {
return storePath.getFullPath();
}
}
package com.test.fastdfs;
import com.test.fastdfs.utils.FastDfsUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
/**
* Class Name TestController ...
*
* @author LiJun
* Created on 2019/10/31 14:02
*/
@Controller
public class TestController {
@Autowired
private FastDfsUtils dfsUtils;
@RequestMapping(value = {"/", "/index"})
public String index() {
return "index";
}
@RequestMapping("/upload1")
@ResponseBody
public String uploadFile(MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
String originalFileName = file.getOriginalFilename();
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String fileName = file.getName();
long fileSize = file.getSize();
System.out.println(originalFileName + "==========" + fileName + "===========" + fileSize + "===============" + extension + "====" + bytes.length);
return dfsUtils.uploadFile(bytes, fileSize, extension);
}
@RequestMapping("/download")
public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
byte[] bytes = dfsUtils.downloadFile(fileUrl);
// 这里只是为了整合fastdfs,所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("1.jpg", "UTF-8"));
response.setCharacterEncoding("UTF-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 上传文件
*/
@PostMapping(value = "/upload2")
public String upload(MultipartFile file) throws Exception {
return dfsUtils.uploadFile(file);
}
}