FastDFS通过java上传文件到服务器

GitHub原文地址点击进入
#一、FastDFS简介及系统环境搭建:点击进入
#二、FastDFS 配置 Nginx 模块及访问测试:点击进入
#三、FastDFS使用流程介绍:
我们在项目中使用fastdfs+nginx+mysql实现上传附件的功能,主要原理就是将附件上传到fastdfs得到一个文件的链接路径url,我们获取到这个url将他以字符串形式保存到我们的mysql中,下载的时候获取到这个url直接打开或者下载附件
FastDFS通过java上传文件到服务器_第1张图片FastDFS通过java上传文件到服务器_第2张图片
#四、实现代码:
1,配置依赖:因为我们使用的maven来管理工程,所以我们需要去添加pom文件依赖



	org.csource
	fastdfs-client-java
	1.27-SNAPSHOT

        
	commons-io        
	commons-io        
	2.4    

注意:由于fastdfs-client-java jar包没有上传到中央仓库,所以需要下载源码进行maven编译再上传到私服,然后通过私服下载,具体流程参照步骤一,或者通过jar包的形式进行下载:
下载地址:点击进入

2,配置信息:我这里是配置在 application.properties 文件中的

#FastDFS配置begin-----------除了fastdfs.tracker_servers,其它配置项都是可选的
fastdfs.connect_timeout_in_seconds=5
fastdfs.network_timeout_in_seconds=30
fastdfs.charset=UTF-8
fastdfs.http_anti_steal_token=false
fastdfs.http_secret_key=FastDFS1234567890
fastdfs.http_tracker_http_port=8070
fastdfs.tracker_servers=192.168.2.200:22122
#FastDFS配置end-----------

FastDFS通过java上传文件到服务器_第3张图片
3,具体实现代码:

/**
  * 上传文件到FastDFS
  *
  * @param file
  */
 @RequestMapping(value = "/fastDFSUpload", method = RequestMethod.POST)
 @ResponseBody
 public void fastDFSUpload(MultipartFile file) {

     String ext_Name = file.getOriginalFilename().split("\\.")[1];
     String file_Name = file.getOriginalFilename().split("\\.")[0];

     byte[] bytes = null;
     try {
         bytes = file.getBytes();
     } catch (IOException e) {
         e.printStackTrace();
     }

     String filePath= uploadFile(bytes, ext_Name, file_Name);
 }

 /**
  * FastDFS实现文件下载
  *
  * @param filePath
  */
 @RequestMapping(value = "/fastDFSDownload", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSDownload(String filePath) {
     try {
         ClientGlobal.initByProperties("application.properties");

         // 链接FastDFS服务器,创建tracker和Stroage
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);
         byte[] b = storageClient.download_file("group1", filePath);
         if (b == null) {
             throw new IOException("文件" + filePath + "不存在");
         }

         String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
         FileOutputStream fileOutputStream = new FileOutputStream("c://" + fileName);
         IOUtils.write(b, fileOutputStream);
         fileOutputStream.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS获取将上传文件信息
  */
 @RequestMapping(value = "/fastDFSGetFileInfo", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSGetFileInfo(String filePath) {
     try {
         // 链接FastDFS服务器,创建tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         FileInfo fi = storageClient.get_file_info("group1", filePath);
         if (fi == null) {
             throw new IOException("文件" + filePath + "不存在");
         }

         log.debug("文件信息=" + fi.toString());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS获取文件名称
  */
 @RequestMapping(value = "/fastDFSGetFileName", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSGetFileName(String filePath) {
     try {
         // 链接FastDFS服务器,创建tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         NameValuePair[] nvps = storageClient.get_metadata("group1", filePath);
         if (nvps == null) {
             throw new IOException("文件" + filePath + "不存在");
         }

         log.debug(nvps[0].getName() + "." + nvps[0].getValue());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 /**
  * FastDFS实现删除文件
  */
 @RequestMapping(value = "/fastDFSDelete", method = RequestMethod.GET)
 @ResponseBody
 public void fastDFSDelete(String filePath) {
     try {
         // 链接FastDFS服务器,创建tracker和Stroage
         ClientGlobal.initByProperties("application.properties");
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         int i = storageClient.delete_file("group1", filePath);
         log.debug(i == 0 ? "删除成功" : "删除失败:" + i);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 public String uploadFile(byte[] byteFile, String ext_file, String file_Name) {

     // 拼接服务区的文件路径
     StringBuffer sbPath = new StringBuffer();
     sbPath.append("http://192.168.2.200/uploads/");
     try {
         // 初始化文件资源
         ClientGlobal.initByProperties("application.properties");

         // 链接FastDFS服务器,创建tracker和Stroage
         TrackerClient trackerClient = new TrackerClient();
         TrackerServer trackerServer = trackerClient.getConnection();

         String storageServerIp = getStorageServerIp(trackerClient, trackerServer);
         StorageServer storageServer = getStorageServer(storageServerIp);
         StorageClient storageClient = new StorageClient(trackerServer, storageServer);

         //利用字节流上传文件
//            NameValuePair[] nvps = new NameValuePair[1];
//            nvps[0] = new NameValuePair(file_Name, ext_file);
         String[] strings = storageClient.upload_file(byteFile, ext_file, null);

         sbPath.append(StrUtil.join("/", strings));
         log.debug("上传路径=" + sbPath.toString());
     } catch (IOException | MyException e) {
         e.printStackTrace();
     }
     return sbPath.toString();
 }

 /**
  * 得到Storage服务
  *
  * @param storageIp
  * @return 返回Storage服务
  */
 private static StorageServer getStorageServer(String storageIp) {
     StorageServer storageServer = null;
     if (storageIp != null && !("").equals(storageIp)) {
         try {
             // ip port store_path下标
             storageServer = new StorageServer(storageIp, 23000, 1);
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     log.debug("——storage server生成");
     return storageServer;
 }

 /**
  * 获得可用的storage IP
  *
  * @param trackerClient
  * @param trackerServer
  * @return 返回storage IP
  */
 private static String getStorageServerIp(TrackerClient trackerClient, TrackerServer trackerServer) {
     String storageIp = null;
     if (trackerClient != null && trackerServer != null) {
         try {
             StorageServer storageServer = trackerClient.getStoreStorage(trackerServer, "group1");
             storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     log.debug("——获取组中可用的storage IP——" + storageIp);
     return storageIp;
 }

#五、效果查看
FastDFS通过java上传文件到服务器_第4张图片
直接就可以集成swagger通过api接口上传文件了,搭建好nginx环境后可以通过返回的url路径访问上传的文件,别的就不再一一演示了,自己去查看效果吧

你可能感兴趣的:(FastDFS)