10、SpringBoot2.0集成FastDFS(十)

简介: 前言:由于本篇博客是建立在上一个博客上写的,所以阅读本篇博客之前需要先看下文件上传功能的实现https://blog.csdn.net/yang_guang3/article/details/100015770

前言:由于本篇博客是建立在上一个博客上写的,所以阅读本篇博客之前需要先看下文件上传功能的实现https://blog.csdn.net/yang_guang3/article/details/100015770

1、引入pom文件:

<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

有些小伙伴在引入该依赖时可能会报错,是因为中央仓库并没有集成该依赖,需要下载该jar包然后打包到本地仓库,下载fastdfs-client-java开发工具包:

https://github.com/happyfish100/fastdfs-client-java

解压后cmd进入该文件下,然后运行下面的Maven指令:

mvn clean install

2、在resources文件夹下新增fdfs_client.conf文件:

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.anti_steal_token = no
http.secret_key = 123456
#FastDFS服务器的IP地址
tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122

3、新增FastDFS核心类:

FastDFSClient:

package com.xhy.xczx.fastdfs;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FastDFSClient {
  private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
  static {
  try {
    String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
    ClientGlobal.init(filePath);
  } catch (Exception e) {
    logger.error("FastDFS Client Init Fail!",e);
  }
  }
  public static String[] upload(FastDFSFile file) {
  logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
  NameValuePair[] meta_list = new NameValuePair[1];
  meta_list[0] = new NameValuePair("author", file.getAuthor());
  long startTime = System.currentTimeMillis();
  String[] uploadResults = null;
  StorageClient storageClient=null;
  try {
    storageClient = getTrackerClient();
    uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
  } catch (IOException e) {
    logger.error("IO Exception when uploadind the file:" + file.getName(), e);
  } catch (Exception e) {
    logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
  }
  logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
  if (uploadResults == null && storageClient!=null) {
    logger.error("upload file fail, error code:" + storageClient.getErrorCode());
  }
  String groupName = uploadResults[0];
  String remoteFileName = uploadResults[1];
  logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
  return uploadResults;
  }
  public static FileInfo getFile(String groupName, String remoteFileName) {
  try {
    StorageClient storageClient = getTrackerClient();
    return storageClient.get_file_info(groupName, remoteFileName);
  } catch (IOException e) {
    logger.error("IO Exception: Get File from Fast DFS failed", e);
  } catch (Exception e) {
    logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  }
  return null;
  }
  public static InputStream downFile(String groupName, String remoteFileName) {
  try {
    StorageClient storageClient = getTrackerClient();
    byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
    InputStream ins = new ByteArrayInputStream(fileByte);
    return ins;
  } catch (IOException e) {
    logger.error("IO Exception: Get File from Fast DFS failed", e);
  } catch (Exception e) {
    logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  }
  return null;
  }
  public static void deleteFile(String groupName, String remoteFileName)
    throws Exception {
  StorageClient storageClient = getTrackerClient();
  int i = storageClient.delete_file(groupName, remoteFileName);
  logger.info("delete file successfully!!!" + i);
  }
  public static StorageServer[] getStoreStorages(String groupName)
    throws IOException {
  TrackerClient trackerClient = new TrackerClient();
  TrackerServer trackerServer = trackerClient.getConnection();
  return trackerClient.getStoreStorages(trackerServer, groupName);
  }
  public static ServerInfo[] getFetchStorages(String groupName,
            String remoteFileName) throws IOException {
  TrackerClient trackerClient = new TrackerClient();
  TrackerServer trackerServer = trackerClient.getConnection();
  return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
  }
  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();
  StorageClient storageClient = new StorageClient(trackerServer, null);
  return  storageClient;
  }
  private static TrackerServer getTrackerServer() throws IOException {
  TrackerClient trackerClient = new TrackerClient();
  TrackerServer trackerServer = trackerClient.getConnection();
  return  trackerServer;
  }
}
FastDFSFile:
public class FastDFSFile {
private String name;
private byte[] content;
private String ext;
private String md5;
private String author;
public FastDFSFile(String name, byte[] content, String ext, String height,
       String width, String author) {
  super();
  this.name = name;
  this.content = content;
  this.ext = ext;
  this.author = author;
}
public FastDFSFile(String name, byte[] content, String ext) {
  super();
  this.name = name;
  this.content = content;
  this.ext = ext;
}
//set和get方法,自动生成
}

在UploadController类中添加以下方法:

private static Logger logger = LoggerFactory.getLogger(UploadController.class);
@RequestMapping("/uploadFile1")
    public ModelAndView uploadFile1(@RequestParam("file") MultipartFile file, ModelAndView modelAndView) {
        modelAndView.setViewName("uploadStatus");
        if (file.isEmpty()) {
            modelAndView.addObject("message","上传失败,请选择一个文件上传");
            return modelAndView;
        }
        try {
            String path=saveFile(file);
            modelAndView.addObject("path","上传成功,文件路径为:" + path);
            modelAndView.addObject("message","上传成功,上传的文件名为:" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
        try {
            fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            logger.error("upload file Exception!",e);
        }
        if (fileAbsolutePath==null) {
            logger.error("upload file failed,please upload again!");
        }
        String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        return path;
    }

然后重启项目,访问:

http://localhost:8081/uploadFile1

测试结果:

显示上传成功,然后访问文件路径,证明上传成功:

该文件的存放位置对应于storage服务器上的

/home/fastdfs/store_path0/data/00/00/wKgZhV1ff36AHWlhAAKh5tVfKAA742.jpg



目录
相关文章
|
8月前
|
Java
springboot整合fastdfs、启动不成功
springboot整合fastdfs、启动不成功
61 0
|
Java 文件存储 Spring
轻松实现Spring Boot与FastDFS的无缝整合
家人们啦!,上篇文章了,我们讲了如何使用docker-compose快速部署fastdfs,在今天的文章中,我将向大家介绍如何将Spring Boot与FastDFS进行无缝整合,以便高效地管理和操作文件存储。通过这个整合,你将能够轻松地在Spring Boot应用程序中实现文件的上传和下载等功能。让我们开始吧
297 0
轻松实现Spring Boot与FastDFS的无缝整合
|
存储 编解码 前端开发
SpringBoot整合FastDFS实现图片的上传
  文件的上传和预览在web开发领域是随处可见,存储的方式有很多,本文采用阿里巴巴余庆大神开发的FastDFS进行文件的存储,FastDFS是一个分布式文件存储系统,可以看我上一篇博文,有安装和配置教程。
189 0
|
存储 负载均衡 Java
SpringBoot集成FastDFS
FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的在线服务,如相册网站、视频网站等等。 FastDFS为互联网量身定制,充分考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性能等指标,使用FastDFS很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务。
|
消息中间件 存储 JSON
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ(下)
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ
169 0
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ(下)
|
SQL 缓存 NoSQL
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ(上)
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ
115 0
面试:第八章:SpringMVC、Springboot、Mybatis、Dubbo、Zookeeper、Redis、Elasticsearch、Nginx 、Fastdfs、ActiveMQ(上)
|
Java
Springboot集成fastdfs完成上传图片,返回url地址
Springboot集成fastdfs完成上传图片,返回url地址
246 0
|
Java 应用服务中间件 网络安全
|
Java 应用服务中间件 Linux

热门文章

最新文章