记:demo------FastDFS实现文件下载 上传 删除

1.添加依赖:springboot实现

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
</parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--为了解决thymeleaf模板中,对html标签要求太严格的问题!-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

        <!--fastdfs客户单的依赖包-->
        <dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client</artifactId>
            <version>1.19.0</version>
        </dependency>
        <dependency>
            <groupId>fastdfs_client</groupId>
            <artifactId>fastdfs_client</artifactId>
            <version>1.25</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.配置文件 application.yml

server:
  port: 8081
spring:
  http:
    multipart:
      max-file-size: 30MB
      max-request-size: 40MB

3.配置文件 dfs.properties

#fastdfs核心配置
connect_timeout= 60
network_timeout= 60
charset= UTF-8
http.tracker_http_port= 8080
http.secret_key= 123456
http.anti_steal_token= false

#配置追踪服务器地址
tracker_server= 192.168.242.128:22122

4.前端页面1 upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>FastDFS文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"/><br/><br/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>

4.前端页面1 status.html

</head>
<body>
<div>
    <h1>FastDFS文件上传状态</h1>

    <div th:if="${msg}">
        <h2 th:text="${msg}"/>
    </div>

    <!--图片回显-->
    <div th:if="${path}">
        <h2 th:text="${path}"/>
        ![在这里插入图片描述]()
    </div>

</div>
</body>
</html>

5.封装文件类

@Data
public class FastDFSFile {

    private String name;//文件名

    private String ext;//文件扩展名

    private byte[] content;//文件内容

    private String author;//文件作者

    public FastDFSFile(String name, String ext, byte[] content) {
        this.name = name;
        this.ext = ext;
        this.content = content;
    }

}

6.工具类

@Slf4j
public class FastDFSClientUtil {

    //初始化获取fdfs_client.conf配置文件路径
    static {
        try {
            String filePath = new ClassPathResource("fast_dfs.conf")
                    .getFile()
                    .getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            log.error("FastDFS Client 初始化失败!", e);
        }
    }

    //文件上传工具类
    public static String[] upload(FastDFSFile file) throws MyException {
        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());

        String[] uploadResults = null;
        StorageClient storageClient = null;
        try {
            storageClient =getTrackerClient();
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (uploadResults == null && storageClient != null) {
            return null;
        }else{
            //String groupName = uploadResults[0];
            //String remoteFileName = uploadResults[1];
            //log.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
            return uploadResults;
        }
    }

    //获取追踪服务器url
    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();
        return new StorageClient(trackerServer, null);
    }

    //获取追踪服务器
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getConnection();
    }

    //获取文件的工具方法
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //下载文件
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            return  new ByteArrayInputStream(fileByte);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        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[] getStorageServerByGroupName(String groupName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    //获取文件服务器信息
    public static ServerInfo[] getServerInfo(String groupName,String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }
}

7.controller层

/**
 * 文件上传的接口
 */
@Controller
public class FastDFSComtroller {
   //跳转到文件上传界面
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String login(){

        return "upload";
    }

    //跳转到文件上传状态界面
    @RequestMapping(value = "/status",method = RequestMethod.GET)
    public String showStatus(){
        return "uploadStatus";
    }
    //跳转到下载界面
    @RequestMapping(value = "/down")
    public String showDownStatus(RedirectAttributes attributes){
        //调取下载方法 //http://192.168.242.128:8080/group1\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx
        String a ="group1";
        String b ="group1\\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx";//group1/M00/00/00/wKjygF0csvmAU6ACAAEy9XHDWws351.jpg
        InputStream path = FastDFSClientUtil.downFile(a,b);
        if (path != null) {
            attributes.addFlashAttribute("msg", "文件下载成功-->" );
            attributes.addFlashAttribute("path", path);
        }else{
            attributes.addFlashAttribute("msg", "文件下载失败");
        }
        return "redirect:status";
    }

    //文件上传接口
    @RequestMapping(value = "/upload")
    public String upload(@RequestBody MultipartFile file, RedirectAttributes attributes){
        if(file.isEmpty()){
            attributes.addFlashAttribute("msg","请选择您要上传的文件!!!!!");
            return "redirect:status";
        }
        //调取上传服务器的方法
        String path = uploadToServer(file);
        if (path != null) {
            attributes.addFlashAttribute("msg", "文件上传成功-->" + file.getOriginalFilename());
            attributes.addFlashAttribute("path", path);
        }else{
            attributes.addFlashAttribute("msg", "文件上传失败");
        }
        return "redirect:status";
    }

    //把文件上传到服务器
    private String uploadToServer(MultipartFile file){
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        //获得文件的拓展名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("." )+ 1);

        try {
            byte[] content = file.getBytes();
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,substring,content);
            String[] upload = FastDFSClientUtil.upload(fastDFSFile);
            if(upload!=null){
                return FastDFSClientUtil.getTrackerUrl() + upload[0] + File.separator + upload[1];
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }

}

8.启动

@SpringBootApplication
public class FastDfsApplication {
    public static void main(String[] args){
        SpringApplication.run(FastDfsApplication.class,args);
    }
}

9.项目结构
在这里插入图片描述
上传结果:
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
org.csource:fastdfs-client-java:1.29-是一个Java语言的FastDFS客户端,用于访问FastDFS分布式文件系统。FastDFS是一个开源的分布式文件系统,具有高性能、高可靠性、可扩展性和易于管理等特点。FastDFS文件分成许多小块,然后存储在多台服务器上,提供了快速的文件上传下载功能。 org.csource:fastdfs-client-java:1.29-是FastDFS的Java语言实现,通过该客户端,我们可以轻松地在Java项目中使用FastDFS进行文件上传下载。它提供了一组简单易用的API,允许我们通过指定文件路径或字节数组来上传文件,并通过文件的标识符来下载文件。同时,我们还可以获取文件的元信息,例如文件大小、创建时间等。 通过该客户端,我们还可以进行文件删除、修改和查询等操作。它提供了丰富的接口方法,可以满足不同的业务需求。此外,该客户端还支持文件的断点续传功能,当网络中断或上传下载过程中出现异常时,我们可以恢复中断的操作,避免重新上传下载整个文件。 org.csource:fastdfs-client-java:1.29-是一个成熟稳定的Java组件,被广泛应用于各种基于Java的项目中。它的源代码是开放的,意味着我们可以根据自己的需求进行修改和定制。此外,它还具有良好的文档和社区支持,我们可以在遇到问题时及时获得帮助和解决方案。 总之,org.csource:fastdfs-client-java:1.29-是一个功能强大、易用的Java客户端,提供了丰富的API和功能,帮助我们轻松地在Java项目中使用FastDFS分布式文件系统。它是一个值得信赖和推荐的工具,可以提高文件操作的效率和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值