分布式微服务架构springcloud+vue实现文件上传功能

首先下载相关源码配好环境

下载源码

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

编译源码成jar本地安装到maven 的本地仓库

mvn install

1 基于Docker搭建FastDFS服务

基于Docker搭建FastDFS服务_Bruce Deeg的博客-CSDN博客FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的在线服务,如相册网站、视频网站等等。FastDFS是纯C语言实现,只支持Linux、FreeBSD等UNIX系统。FastDFS的两个核心概念分别是:Tracker(跟踪器)、Storage(存储节点)首先启动dockersystemctl start docker1.下载FastDFS文件系统的dohttps://blog.csdn.net/weixin_62595121/article/details/123901855?spm=1001.2014.3001.5502

2 依赖


    org.csource
    fastdfs-client-java
    1.27-SNAPSHOT

3 创建一个fdfs_client.conf文件 文件名自己定义

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 192.168.0.666:22122 #端口号填写自己的

4 两个工具类

4.1 FastDFSFile实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class FastDFSFile implements Serializable {
    private String name;
    private byte[] content;
    private String ext;
    private String md5;
    private String author;
                       //文件名            //文件内容字节码 文件名的后缀
    public FastDFSFile(String fileName, byte[] file_buff, String ext) {
        this.name = fileName;
        this.content = file_buff;
        this.ext = ext;
    }

}

4.2 FastDFSUtil工具类

@Slf4j
public class FastDFSUtil {
    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ;
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            log.error("FastDFS Client Init Fail!", e);
        }
    }
    // 文件上传
    public static String[] upload(FastDFSFile file) {
        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());

        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) {
            log.error("IO Exception when uploadind the file:" + file.getName(), e);
        } catch (Exception e) {
            log.error("Non IO Exception when uploadind the file:" + file.getName(), e);
        }
        log.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

        if (uploadResults == null && storageClient != null) {
            log.error("upload file fail, error code:" + storageClient.getErrorCode());
        }
        //组名
        String groupName = uploadResults[0];
        //远程文件名 上传之后生成的新的一个文件名
        String remoteFileName = uploadResults[1];

        log.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) {
            log.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            log.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) {
            log.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            log.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);
        log.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;
    }

5 FileController

@Api(tags = {"文件操作接口"})
@RestController
@RequestMapping("/file")
@CrossOrigin // 对这个类进行跨域处理
public class FileController {

    @ApiOperation("文件上传")
    @PostMapping("/upload")                      //文件
    public Result> uploadFile(MultipartFile file){
        //文件名
        String filename = file.getOriginalFilename();
        //文件后缀
        String ext = filename.substring(filename.lastIndexOf(".")+1);//截取jpg .不要

        FastDFSFile fastDFSFile = null;
        try {
            //准备文件上传对象
            fastDFSFile = new FastDFSFile(filename,file.getBytes(),ext);
            //文件上传
            String[] uploadResult = FastDFSUtil.upload(fastDFSFile);
            if(uploadResult !=null && uploadResult.length == 2){
                //组名
                String groupName = uploadResult[0];
                //远程文件名 上传之后生成的新的一个文件名
                String remoteFileName = uploadResult[1];
                                //服务器地址
                String fileUrl = FastDFSUtil.getTrackerUrl()+ groupName+"/"+remoteFileName;
                Map data = new HashMap<>();
                data.put("groupName",groupName);
                data.put("remoteFileName",remoteFileName);
                data.put("fileUrl",fileUrl);
                return Result.success("文件上传成功",data);
            }else{
                return Result.fail(20009,"文件上传失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(20009,"文件上传失败!");
        }
    }
}

你可能感兴趣的:(spring,java,数据库开发,idea,maven)