1.添加依赖:springboot实现
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--为了解决thymeleaf模板中,对html标签要求太严格的问题!-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!--fastdfs客户单的依赖包-->
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>1.19.0</version>
</dependency>
<dependency>
<groupId>fastdfs_client</groupId>
<artifactId>fastdfs_client</artifactId>
<version>1.25</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
2.配置文件 application.yml
server:
port: 8081
spring:
http:
multipart:
max-file-size: 30MB
max-request-size: 40MB
3.配置文件 dfs.properties
#fastdfs核心配置
connect_timeout= 60
network_timeout= 60
charset= UTF-8
http.tracker_http_port= 8080
http.secret_key= 123456
http.anti_steal_token= false
#配置追踪服务器地址
tracker_server= 192.168.242.128:22122
4.前端页面1 upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>FastDFS文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
4.前端页面1 status.html
</head>
<body>
<div>
<h1>FastDFS文件上传状态</h1>
<div th:if="${msg}">
<h2 th:text="${msg}"/>
</div>
<!--图片回显-->
<div th:if="${path}">
<h2 th:text="${path}"/>
![在这里插入图片描述]()
</div>
</div>
</body>
</html>
5.封装文件类
@Data
public class FastDFSFile {
private String name;//文件名
private String ext;//文件扩展名
private byte[] content;//文件内容
private String author;//文件作者
public FastDFSFile(String name, String ext, byte[] content) {
this.name = name;
this.ext = ext;
this.content = content;
}
}
6.工具类
@Slf4j
public class FastDFSClientUtil {
//初始化获取fdfs_client.conf配置文件路径
static {
try {
String filePath = new ClassPathResource("fast_dfs.conf")
.getFile()
.getAbsolutePath();
ClientGlobal.init(filePath);
} catch (Exception e) {
log.error("FastDFS Client 初始化失败!", e);
}
}
//文件上传工具类
public static String[] upload(FastDFSFile file) throws MyException {
log.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
NameValuePair[] meta_list = new NameValuePair[1];
meta_list[0] = new NameValuePair("author", file.getAuthor());
String[] uploadResults = null;
StorageClient storageClient = null;
try {
storageClient =getTrackerClient();
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
} catch (IOException e) {
e.printStackTrace();
}
if (uploadResults == null && storageClient != null) {
return null;
}else{
//String groupName = uploadResults[0];
//String remoteFileName = uploadResults[1];
//log.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
return uploadResults;
}
}
//获取追踪服务器url
public static String getTrackerUrl() throws IOException {
return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";
}
//获取追踪服务器客户端
private static StorageClient getTrackerClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
return new StorageClient(trackerServer, null);
}
//获取追踪服务器
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
return trackerClient.getConnection();
}
//获取文件的工具方法
public static FileInfo getFile(String groupName, String remoteFileName) {
try {
StorageClient storageClient = getTrackerClient();
return storageClient.get_file_info(groupName, remoteFileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//下载文件
public static InputStream downFile(String groupName, String remoteFileName) {
try {
StorageClient storageClient = getTrackerClient();
byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
return new ByteArrayInputStream(fileByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//删除文件
public static void deleteFile(String groupName, String remoteFileName)
throws Exception {
StorageClient storageClient = getTrackerClient();
int i = storageClient.delete_file(groupName, remoteFileName);
log.info("delete file successfully!!!" + i);
}
//根据组名获取存储文件服务器
public static StorageServer[] getStorageServerByGroupName(String groupName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getStoreStorages(trackerServer, groupName);
}
//获取文件服务器信息
public static ServerInfo[] getServerInfo(String groupName,String remoteFileName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
}
}
7.controller层
/**
* 文件上传的接口
*/
@Controller
public class FastDFSComtroller {
//跳转到文件上传界面
@RequestMapping(value = "/",method = RequestMethod.GET)
public String login(){
return "upload";
}
//跳转到文件上传状态界面
@RequestMapping(value = "/status",method = RequestMethod.GET)
public String showStatus(){
return "uploadStatus";
}
//跳转到下载界面
@RequestMapping(value = "/down")
public String showDownStatus(RedirectAttributes attributes){
//调取下载方法 //http://192.168.242.128:8080/group1\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx
String a ="group1";
String b ="group1\\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx";//group1/M00/00/00/wKjygF0csvmAU6ACAAEy9XHDWws351.jpg
InputStream path = FastDFSClientUtil.downFile(a,b);
if (path != null) {
attributes.addFlashAttribute("msg", "文件下载成功-->" );
attributes.addFlashAttribute("path", path);
}else{
attributes.addFlashAttribute("msg", "文件下载失败");
}
return "redirect:status";
}
//文件上传接口
@RequestMapping(value = "/upload")
public String upload(@RequestBody MultipartFile file, RedirectAttributes attributes){
if(file.isEmpty()){
attributes.addFlashAttribute("msg","请选择您要上传的文件!!!!!");
return "redirect:status";
}
//调取上传服务器的方法
String path = uploadToServer(file);
if (path != null) {
attributes.addFlashAttribute("msg", "文件上传成功-->" + file.getOriginalFilename());
attributes.addFlashAttribute("path", path);
}else{
attributes.addFlashAttribute("msg", "文件上传失败");
}
return "redirect:status";
}
//把文件上传到服务器
private String uploadToServer(MultipartFile file){
//获取文件的名字
String originalFilename = file.getOriginalFilename();
//获得文件的拓展名
String substring = originalFilename.substring(originalFilename.lastIndexOf("." )+ 1);
try {
byte[] content = file.getBytes();
FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,substring,content);
String[] upload = FastDFSClientUtil.upload(fastDFSFile);
if(upload!=null){
return FastDFSClientUtil.getTrackerUrl() + upload[0] + File.separator + upload[1];
}
} catch (IOException e) {
e.printStackTrace();
}catch (MyException e) {
e.printStackTrace();
}
return null;
}
}
8.启动
@SpringBootApplication
public class FastDfsApplication {
public static void main(String[] args){
SpringApplication.run(FastDfsApplication.class,args);
}
}
9.项目结构
上传结果: