Almacenamiento de archivos distribuido: FastDFS realiza la carga de archivos

instalación

Consulte mi artículo anterior docker install fastdfs

Módulo de construcción
confiar
  <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>0.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba.nacos</groupId>
        <artifactId>nacos-client</artifactId>
        <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>
            <!--MySQL数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
fdfs_client.conf
connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
tracker_server = 192.168.93.128:22122  #Linux地址
application.yml
server:
  port: 9008     #访问路径 
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  application:
    name: nacos-provider  #注册中心中出现的名字
  datasource:    #地址改成自己的
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.93.128:3308/changgou-goods?   useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.93.128:8848         #nacos注册中心服务端
feign:
  hystrix:
    enabled: true

Configurar la información de conexión del servidor nacos

Comenzar la clase

Agregar comentarios para cliente nacos

package com.xyy.file;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient  //开启nacos的客户端
public class FileApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(FileApplication.class,args);
    }
}

clase de entidad de archivo: esta es una clase de herramienta
package com.changgou.file.util;

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;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public byte[] getContent() {
    
    
        return content;
    }

    public void setContent(byte[] content) {
    
    
        this.content = content;
    }

    public String getExt() {
    
    
        return ext;
    }

    public void setExt(String ext) {
    
    
        this.ext = ext;
    }

    public String getMd5() {
    
    
        return md5;
    }

    public void setMd5(String md5) {
    
    
        this.md5 = md5;
    }

    public String getAuthor() {
    
    
        return author;
    }

    public void setAuthor(String author) {
    
    
        this.author = author;
    }
}
Herramientas cliente
package com.changgou.file.util;
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);

    /***
     * 初始化加载FastDFS的TrackerServer配置
     */
    static {
    
    
        try {
    
    
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
    
    
            logger.error("FastDFS Client Init Fail!",e);
        }
    }

    /***
     * 文件上传
     * @param file
     * @return 1.文件的组名  2.文件的路径信息
     */
    public static String[] upload(FastDFSFile file) {
    
    
        //获取文件的作者
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());

        //接收返回数据
        String[] uploadResults = null;
        StorageClient storageClient=null;
        try {
    
    
            //创建StorageClient客户端对象
            storageClient = getTrackerClient();

            /***
             * 文件上传
             * 1)文件字节数组
             * 2)文件扩展名
             * 3)文件作者
             */
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
    
    
            logger.error("Exception when uploadind the file:" + file.getName(), e);
        }

        if (uploadResults == null && storageClient!=null) {
    
    
            logger.error("upload file fail, error code:" + storageClient.getErrorCode());
        }
        //获取组名
        String groupName = uploadResults[0];
        //获取文件存储路径
        String remoteFileName = uploadResults[1];
        return uploadResults;
    }

    /***
     * 获取文件信息
     * @param groupName:组名
     * @param remoteFileName:文件存储完整名
     * @return
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {
    
    
        try {
    
    
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
    
    
            logger.error("Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /***
     * 文件下载
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
    
    
        try {
    
    
            //创建StorageClient
            StorageClient storageClient = getTrackerClient();

            //下载文件
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (Exception e) {
    
    
            logger.error("Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /***
     * 文件删除
     * @param groupName
     * @param remoteFileName
     * @throws Exception
     */
    public static void deleteFile(String groupName, String remoteFileName)
            throws Exception {
    
    
        //创建StorageClient
        StorageClient storageClient = getTrackerClient();

        //删除文件
        int i = storageClient.delete_file(groupName, remoteFileName);
    }

    /***
     * 获取Storage组
     * @param groupName
     * @return
     * @throws IOException
     */
    public static StorageServer[] getStoreStorages(String groupName)
            throws IOException {
    
    
        //创建TrackerClient
        TrackerClient trackerClient = new TrackerClient();
        //获取TrackerServer
        TrackerServer trackerServer = trackerClient.getConnection();
        //获取Storage组
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    /***
     * 获取Storage信息,IP和端口
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws IOException
     */
    public static ServerInfo[] getFetchStorages(String groupName,
                                                String remoteFileName) throws IOException {
    
    
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    /***
     * 获取Tracker服务地址
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException {
    
    
        return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
    }
    /***
     * 获取Storage客户端
     * @return
     * @throws IOException
     */
    private static StorageClient getTrackerClient() throws IOException {
    
    
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return  storageClient;
    }
    /***
     * 获取Tracker
     * @return
     * @throws IOException
     */
    private static TrackerServer getTrackerServer() throws IOException {
    
    
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return  trackerServer;
    }
}
controlador
package com.xyy.file.controller;
import com.xyy.common.pojo.Result;
import com.xyy.common.pojo.StatusCode;
import com.xyy.file.util.FastDFSClient;
import com.xyy.file.util.FastDFSFile;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
 * FastDFS上传文件
 */
@RestController    //restController=Controller+ResponseBody
@RequestMapping("/fast")
public class FileController {
    
    

    @PostMapping("/upload")
     public Result UploadFile(MultipartFile file) throws IOException {
    
    

        try {
    
    
            if (file == null) {
    
    
                throw  new RuntimeException("文件不存在");
            }
            //获取文件的名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
    
    
                throw  new RuntimeException("文件不存在");
            }
            //获取上传文件的 后缀名
            String endName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //获取文件内容
            byte[] content = file.getBytes();
            //封装到一个实体类中
            FastDFSFile dfsFile = new FastDFSFile(originalFilename, content, endName);
            //文件上传
            String[] strings = FastDFSClient.upload(dfsFile);
            //获取文件所在组名
            String Url = FastDFSClient.getTrackerUrl()+strings[0]+"/"+strings[1];
            System.out.println(Url);
            return new Result(true, StatusCode.OK,"文件上传成功",Url);
        }catch (Exception e){
    
    
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }
}

Diagrama de prueba

El nombre debe completarse en el archivo primero, hay muchos hoyos aquíInserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/weixin_47785112/article/details/108486399
Recomendado
Clasificación