系统中如何配置FastDFS资源服务器

  1. 导入依赖

            <!--fastdfs-->
            <dependency>
                <groupId>cn.bestwu</groupId>
                <artifactId>fastdfs-client-java</artifactId>
                <version>1.27</version>
            </dependency>
    
            <!--用来获取文件扩展名的包-->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.8.0</version>
            </dependency>
    
  2. 编写一个配置文件fdfs_client.conf

    tracker_server=service-file-primary.java.itsource.cn:22122
    #22122是tracker的端口 - 上传
    #访问直接使用域名:123.207.27.208
    
    
  3. 编写FastDFS的工具类

    package com.zcy.jkcc.util;
    
    
    import org.csource.fastdfs.*;
    
    /**
     * fastDfs工具类
     */
    public class FastDfsUtils {
    
        //从classpath:resources中的内容最终会编译到classpath下
        public static String CONF_FILENAME  = FastDfsUtils.class.getClassLoader()
                .getResource("fdfs_client.conf").getFile();
    
    
        /**
         * 上传文件
         * @param file
         * @param extName
         * @return
         */
        public static  String upload(byte[] file,String extName) {
    
            try {
                ClientGlobal.init(CONF_FILENAME);
    
                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;
    
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);
    
                String fileIds[] = storageClient.upload_file(file,extName,null);
    
                System.out.println(fileIds.length);
                System.out.println("组名:" + fileIds[0]);
                System.out.println("路径: " + fileIds[1]);
                //  /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
                return  "/"+fileIds[0]+"/"+fileIds[1];
    
            } catch (Exception e) {
                e.printStackTrace();
                return  null;
            }
        }
        /**
         * 上传文件
         * @param extName
         * @return
         */
        public static  String upload(String path,String extName) {
    
            try {
                ClientGlobal.init(CONF_FILENAME);
                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);
                String fileIds[] = storageClient.upload_file(path, extName,null);
    
                System.out.println(fileIds.length);
                System.out.println("组名:" + fileIds[0]);
                System.out.println("路径: " + fileIds[1]);
                return  "/"+fileIds[0]+"/"+fileIds[1];
    
            } catch (Exception e) {
                e.printStackTrace();
                return  null;
            }
        }
    
        /**
         * 下载文件
         * @param groupName
         * @param fileName
         * @return
         */
        public static byte[] download(String groupName,String fileName) {
            try {
    
                ClientGlobal.init(CONF_FILENAME);
    
                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;
    
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);
                byte[] b = storageClient.download_file(groupName, fileName);
                return  b;
            } catch (Exception e) {
                e.printStackTrace();
                return  null;
            }
        }
    
    
        /**
         * 删除文件
         * @param groupName
         * @param fileName
         */
        public static void delete(String groupName,String fileName){
            try {
                ClientGlobal.init(CONF_FILENAME);
    
                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;
    
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);
                int i = storageClient.delete_file(groupName,fileName);
                System.out.println( i==0 ? "删除成功" : "删除失败:"+i);
            } catch (Exception e) {
                e.printStackTrace();
                throw  new RuntimeException("删除异常,"+e.getMessage());
            }
        }
      
    }
    
    
  4. 编写对接前端的controller接口

    package com.zcy.jkcc.controller;
    
    
    import com.zcy.jkcc.result.JsonResult;
    import com.zcy.jkcc.util.FastDfsUtils;
    import org.apache.commons.io.FilenameUtils;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    
    /**
     * fastDfs工具类
     */
    @RestController
    @RequestMapping("/fastdfs")
    public class FastDfsController {
    
        @PostMapping("/upload")
        public JsonResult upload(@RequestParam("file") MultipartFile file) throws IOException {
            // 1.从复杂对象中获取到文件的byte数组
            byte[] bytes = file.getBytes();
            // 2.getOriginalFilename():获取文件的原始名称
            String originalFilename = file.getOriginalFilename();
            // 3.利用coomonIo工具的方法获取到文件的后缀
            String extension = FilenameUtils.getExtension(originalFilename);
            // 4.调用上传工具上传文件
            String fileName = FastDfsUtils.upload(bytes, extension);
            // 5.响应文件名称
            return JsonResult.success(fileName);
        }
    
        @DeleteMapping("/delete")
        public JsonResult delete(String path) throws IOException {
            // /group1/M00/00/2F/oYYBAGRxyKiAcRjaAA5Kws9ji_k408.gif
    
            // group1/M00/00/2F/oYYBAGRxyKiAcRjaAA5Kws9ji_k408.gif
            path = path.substring(1);
            // 只要goup1
            String group = path.substring(0, path.indexOf("/"));
    
            // group1/M00/00/2F/oYYBAGRxyKiAcRjaAA5Kws9ji_k408.gif
            String fileName = path.substring(path.indexOf("/") + 1);
    
            // 4.调用上传工具上传文件
            FastDfsUtils.delete(group, fileName);
            // 5.响应文件名称
            return JsonResult.success();
        }
    
    }
    
    
  5. 然后就是前端配置一个element组件upload,来实现对接后端接口

              <el-upload
                  class="upload-demo"
                  action="http://localhost:10010/jkcc/course/fastdfs/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  :limit=1
                  accept=".jpg,.jpeg,.png,.gif"
                  list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
              </el-upload>
    
  6. 其中上传,删除等事件也要编写对应的方法

    //文件上传的业务逻辑
        handleSuccess(response, file, fileList) {
          this.saveForm.headImg = this.imagePrefix + response.data;
          this.fileList = [];
          this.fileList.push({"url": this.saveForm.headImg});
        },
    
        //文件删除的业务逻辑
        handleRemove(file, fileList) {
          var filePath = file.response.data;
          this.$http.delete("course/fastdfs/delete/?path=" + filePath)
              .then(res => {
                if (res.data.success) {
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                  this.fileList = [];
                } else {
                  this.$message({
                    message: '删除失败!',
                    type: 'error'
                  });
                }
              })
        },
    
        //图片预览
        handlePreview(file) {
          console.log(file);
        },
    
  7. 记得在模型数据层加上一个fileList: [],这个是用来展示图片的列表,最好在添加的时候先将其置空,在编辑时如果需要回显也可以先将它置空然后再执行this.fileList.push({“url”: this.saveForm.headImg});将它回显出来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值