美文网首页
FastDFS文件上传实现

FastDFS文件上传实现

作者: 月哥说了算 | 来源:发表于2019-08-15 01:20 被阅读0次

文件信息封装

文件上传一般都有文件的名字、文件的内容、文件的扩展名、文件的md5值、文件的作者等相关属性,我们可以创建一个对象封装这些属性,代码如下:

public class FastDFSFile {
    //文件名字
    private String name;
    //文件内容
    private byte[] content;
    //文件扩展名
    private String ext;
    //文件MD5摘要值
    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;
    }

    // getter and setter ...
}

文件上传的工具类

package com.changgou.file.util;
import com.changgou.file.pojo.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * @author :gzy
 * @date :Created in 2019/8/13
 * @description :
 * @version: 1.0
 */

public class FastDFSClient {
    private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    private static TrackerClient trackerClient = null;

    private static StorageClient1 storageClient1 = null;

    private static TrackerServer trackerServer = null;

    private static StorageServer storageServer = null;

    //静态代码块   为了上传文件  初始化加载文件的上传配置文件  (文件中包含  上传文件的地址 连接时间 读取时间 编码集 等
    static {
        try {
            //spring提供的类用来处理classpath下的资源,fdfs_client.conf就在classath下。这里获取绝对路径
            String absolutePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            //jar包中的全局类,底层利用流加载配置信息,流要求路径为绝对路径
            ClientGlobal.init(absolutePath);
             //创建跟踪器对象
            trackerClient = new TrackerClient();
            //连接(保存让你连接存储节点的地址)
            trackerServer = trackerClient.getConnection();
            //创建storage客户端,第二个参数个人感觉没什么用所以传个空值意思下
            storageClient1 = new StorageClient1(trackerServer, storageServer);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ClientGlobal is fail:{}",e.getMessage());
        }

    }

    /**
     * 上传文件
     *
     * @param file
     * @return 文件的路径
     */
    public static String uploadFile(FastDFSFile file){
        System.out.println("上传文件");
        NameValuePair[] nameValuePairs = new NameValuePair[1];
        nameValuePairs[0] = new NameValuePair(file.getAuthor());
        try {
            return storageClient1.upload_file1(file.getContent(),file.getExt(),nameValuePairs);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("upload file is fail: {} ",e.getMessage());
        }
        return null;

    }

    /**
     * 下载文件
     * @param path
     * @return  文件对象
     */
    public static InputStream downFile(String path){

        try {
            byte[] bytes = storageClient1.download_file1(path);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e){
            e.getStackTrace();
            logger.error("download file is fail : {}" ,e.getMessage());
        }


        return null;
    }


    /**
     *  删除文件
     * @param path
     *
     */
    public static void deleteFile(String path){

        try {
            storageClient1.delete_file1(path);
        } catch (Exception e)  {
            e.printStackTrace();
            logger.error("delete file is fail : {}",e.getMessage());
        }
    }
    /***
     * 获取Tracker服务地址
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException {
        return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
    }
}

文件上传

创建一个FileController,在该控制器中实现文件上传操作,代码如下:

package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * @author :gzy
 * @date :Created in 2019/8/13
 * @description :
 * @version: 1.0
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
//打印日志
    private Logger logger=LoggerFactory.getLogger(FileController.class);
    @RequestMapping("/updown")
    public Result updownfile(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
//阿帕奇的根据文件名称获取文件后缀名
        String extension = FilenameUtils.getExtension(originalFilename);
        try {
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,file.getBytes(),extension);
            String path = FastDFSClient.uploadFile(fastDFSFile);
            System.out.println(FastDFSClient.getTrackerUrl()+path);
            return new Result(true,StatusCode.OK,"上传成功",path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

相关文章

网友评论

      本文标题:FastDFS文件上传实现

      本文链接:https://www.haomeiwen.com/subject/llaojctx.html