SpringBoot集成FTP

news2024/7/6 20:16:56

1.加入核心依赖

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.8.0</version>
        </dependency>

完整依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <!-- hutool -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.22</version>
        </dependency>
    </dependencies>

2.配置文件

ftp:
    host: 127.0.0.1
    port: 21
    username: root
    password: root

3.FTP配置类

package com.example.config;

import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lenovo
 */
@Configuration
public class FTPConfig {

    @Value("${ftp.host}")
    private String host;

    @Value("${ftp.port}")
    private int port;

    @Value("${ftp.username}")
    private String username;

    @Value("${ftp.password}")
    private String password;

    @Bean
    public FTPClient ftpClient() {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.enterLocalPassiveMode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ftpClient;
    }
}

4.Service层

package com.example.service;

import cn.hutool.crypto.digest.MD5;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Service
public interface FTPService {


    public boolean uploadFile(MultipartFile file) ;


    public boolean downloadFile(String remoteFilePath, String localFilePath);

    public boolean deleteFile(String remoteFilePath);


}

实现类:

package com.example.service.impl;

import com.example.service.FTPService;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

@Service
public class FTPServiceImpl implements FTPService {

    @Autowired
    private FTPClient ftpClient;

    @Override
    public boolean uploadFile(MultipartFile file) {
        try {
            String remoteFilePath = "/w/n";
            ftpClient.enterLocalPassiveMode(); // 设置Passive Mode
            ftpClient.setBufferSize(1024 * 1024); // 设置缓冲区大小为1MB
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置传输模式为二进制
            createRemoteDirectory(ftpClient, remoteFilePath);
            // 切换工作目录
            boolean success = ftpClient.changeWorkingDirectory(remoteFilePath);
            if (!success) {
                System.out.println("切换工作目录失败:" + remoteFilePath);
                return false;
            }

            if (file.isEmpty()) {
                System.out.println("上传的文件为空");
                return false;
            }

            String s = md5(Objects.requireNonNull(file.getOriginalFilename()));
            success = ftpClient.storeFile(s, file.getInputStream());

            if (success) {
                System.out.println("文件上传成功");
            } else {
                System.out.println("文件上传失败");
            }
            return success;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败:" + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean downloadFile(String remoteFilePath, String localFilePath) {
        try {
            boolean b = ftpClient.retrieveFile(remoteFilePath, Files.newOutputStream(Paths.get(localFilePath)));
            System.out.println(b);
            return b;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteFile(String remoteFilePath) {
        try {
            return ftpClient.deleteFile(remoteFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 创建文件夹(多层也可创建) 
    public void createRemoteDirectory(FTPClient ftpClient, String remotePath) throws IOException {
        String[] dirs = remotePath.split("/");
        String tempDir = "";
        for (String dir : dirs) {
            if (dir.isEmpty()) {
                continue;
            }
            tempDir += "/" + dir;
            if (!ftpClient.changeWorkingDirectory(tempDir)) {
                if (!ftpClient.makeDirectory(tempDir)) {
                    throw new IOException("Failed to create remote directory: " + tempDir);
                }
                ftpClient.changeWorkingDirectory(tempDir);
            }
        }
    }

    private static String md5(String fileN) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(fileN.getBytes());
            // 将字节数组转换为十六进制字符串
            StringBuilder str = new StringBuilder();
            for (byte b : digest) {
                str.append(String.format("%02x", b));
            }
            fileN = str.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return fileN;
    }
}

5.Controller层

package com.example.controller;

import com.example.service.FTPService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/ftp")
public class FTPController {

    @Autowired
    private FTPService ftpService;

    @PostMapping("/upload")
    public String uploadFile(MultipartFile file) {
        if (ftpService.uploadFile(file)) {
            return "File uploaded successfully!";
        } else {
            return "Failed to upload file!";
        }
    }

    @GetMapping("/download")
    public String downloadFile(String remoteFilePath, String localFilePath) {
        if (ftpService.downloadFile(remoteFilePath, localFilePath)) {
            return "File downloaded successfully!";
        } else {
            return "Failed to download file!";
        }
    }

    @DeleteMapping("/delete")
    public String deleteFile(@RequestParam String remoteFilePath) {
        if (ftpService.deleteFile(remoteFilePath)) {
            return "File deleted successfully!";
        } else {
            return "Failed to delete file!";
        }
    }
}

6.运行效果

以上就创建好了一个小demo,快去试试吧。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1611612.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

(四)SQL面试题(连续登录、近N日留存)学习简要笔记 #CDA学习打卡

目录 一. 连续登录N天的用户数量 1&#xff09;举例题目 2&#xff09;分析思路 3&#xff09;解题步骤 &#xff08;a&#xff09;Step1&#xff1a;选择12月的记录&#xff0c;并根据用户ID和登录日期先去重 &#xff08;b&#xff09;Step2&#xff1a;创建辅助列a_rk…

maven问题汇总

​ 1、报错 failed to transfer from http://0.0.0.0/ during a previous attempt. com.byd.xxx:xxx-parent:pom:1.1.0-SNAPSHOT failed to transfer from http://0.0.0.0/ during a previous attempt. This failure was cached in the local repository and resolution is no…

K8S哲学 - Pod、RC、RS、deployment

pod&#xff08;最小的可部署单元&#xff09; 容器组&#xff08;运行一个或多个容器&#xff09; Pod(容器组&#xff09;是Kubernetes 中最小的可部署单元。 一个Pod(容器组&#xff09;包含了一个应用程序容器&#xff08;某些情况下是多个容器&#xff09;、存储资源、 一…

C++三大特性之一:继承

文章目录 前言一、继承方式二、继承类型继承中构造和析构的顺序继承中的内存分配多继承语法(非重点)继承中同名静态成员的处理继承一般在哪里用到进阶&#xff1a;菱形继承和虚拟继承 总结 前言 C三大特性&#xff1a;继承、多态和封装。继承是面向对象编程的一个核心概念&…

JavaScript【关系与逻辑运算符】

关系运算符 关系运算符用于比较两个值之间的关系&#xff0c;并根据比较结果返回布尔值&#xff08;true或false&#xff09; 源码 relation-operator<script>//关系运算符 > < > < ! !//根据运算符两边值的关系返回true正确或false错误console.log(1&…

SQLite轻量级会话扩展(三十四)

返回&#xff1a;SQLite—系列文章目录 上一篇&#xff1a;SQLite R*Tree 模块&#xff08;三十三&#xff09; 下一篇&#xff1a;SQLite—系列文章目录 1. 引言 会话扩展提供了一种方便记录的机制 对 SQLite 数据库中某些表的部分或全部更改&#xff0c;以及 将这些…

[阅读笔记18][CITING]LARGE LANGUAGE MODELS CREATE CURRICULUM FOR INSTRUCTION TUNING

这篇论文是23年10月提交到arxiv上的&#xff0c;也是用大模型蒸馏小模型的思路。 作者在这篇论文中提出了课程指令微调&#xff0c;大体流程如下图所示&#xff0c;教师模型给出一个问题&#xff0c;让学生模型回答一下&#xff0c;这时候学生回答大概率不够准确&#xff0c;这…

4.2冰达机器人:视觉实例-机器人视觉循线、视觉实例-调整循线颜色

4.2.10a视觉实例-机器人视觉循线 本节内容演示一个机器人视觉的视觉循线实例 准备工作&#xff1a;布置一块区域作为循线场所&#xff0c;如下图所示。用蓝色胶带在地面贴一条路线&#xff08;机器人极限转弯半径0.5m&#xff0c;不要贴得过于曲折&#xff09;&#xff0c;将…

MINIO安装的方法(WindowsLiunx)

2 minio安装教程 注&#xff1a;官方中文文档&#xff1a;MinIO对象存储 Windows — MinIO中文文档 | MinIO Windows中文文档 Liunx 安装方&#xff1a;MinIO对象存储 Linux — MinIO中文文档 | MinIO Linux中文文档 2.1 下载地址 https://dl.min.io/server/minio/…

vlan 和 trunk实验

VLAN&#xff08;Virtual Local Area Network&#xff09;&#xff0c;即虚拟局域网&#xff0c;是一种网络技术&#xff0c;它的主要原理是将物理网络划分为多个逻辑子网&#xff0c;每个子网形成一个独立的广播域。这样&#xff0c;VLAN内的主机间通信就像在同一个局域网内一…

第二届 Oceanbase 开发者大会 实录

第二届 Oceanbase 开发者大会 实录 今天很有幸参加了Oceanbase 开发者大会&#xff0c;我是真的我一开始还不知道什么是Oceanbase &#xff0c;直到我开了会才知道。看来真的需要多参加一些这样活动。 会议议程 我们科普一下什么是Oceanbase OceanBase 是阿里巴巴集团推出…

Junit 高级-ApiHug准备-测试篇-011

&#x1f917; ApiHug {Postman|Swagger|Api...} 快↑ 准√ 省↓ GitHub - apihug/apihug.com: All abou the Apihug apihug.com: 有爱&#xff0c;有温度&#xff0c;有质量&#xff0c;有信任ApiHug - API design Copilot - IntelliJ IDEs Plugin | Marketplace 涉及到 …

MYSQL之增删改查(下)

前言&#xff1a; 以下是MySQL最基本的增删改查语句&#xff0c;很多IT工作者都必须要会的命令&#xff0c;也 是IT行业面试最常考的知识点&#xff0c;由于是入门级基础命令&#xff0c;所有所有操作都建立在单表 上&#xff0c;未涉及多表操作。 4.3 高级查询 4.3.1 聚合函…

【python】使用python和selenium实现某平台自动化上传作品的全步骤

第一&#xff0c;我们需要下载python并安装 下载地址&#xff1a;https://www.python.org/downloads/release/python-3123/ 3.x版本的python自带pip工具&#xff0c;因此不需要额外下载。 ModuleNotFoundError: No module named seleniumpip用于下载python适用的各类模块&…

最小化横穿北达科他州的直排轮滑补水次数

最小化横穿北达科他州的直排轮滑补水次数 问题定义算法设计伪代码C代码示例策略的正确性和运行时间分析结论 问题定义 Gekko教授计划使用直排轮滑从明尼苏达州东部边境的大福克斯市出发&#xff0c;横穿北达科他州&#xff0c;抵达靠近蒙大拿州西部边境的威利斯顿市。他计划携…

24华中杯ABC题更新完成,B题将提供论文参考,AC题将在下午完成论文

以下内容&#xff0c;将在文章最后放置链接 2024华中杯A题12页思路数据可执行代码参考论文https://mbd.pub/o/bread/ZZ6am5dw 2024华中杯B题24页思路数据可执行代码参考论文https://mbd.pub/o/bread/ZZ6am5hp 2024华中杯C题10页思路数据可执行代码参考论文https://mbd.pub/o/br…

Nginx part2.1

目录 搭建目录网页 为网页设置用户登录 做一个文件目录网页&#xff0c;并进行登陆 示范 搭建目录网页 启动nginx&#xff1a; systemctl start nginx 开机自启动nginx&#xff1a; systemctl enable nginx 启动完服务后&#xff0c;查看自己的nginx的状态&#xff1a;sys…

volatility内存取证

记录一道volatility内存取证的题目&#xff0c;第一次遇到&#xff0c;现场把环境搞出来&#xff0c;现记录一些操作指令。 一、安装volatility3 1、新建一个kali虚拟机 新建的过程不再赘述。 2、下载volatility3 GitHub - volatilityfoundation/volatility3: Volatility …

基于Springboot的职称评审管理系统

基于SpringbootVue的获取源码 联系方式 &#x1f447;&#x1f3fb;的设计与实现 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringbootMybatis工具&#xff1a;IDEA、Maven、Navicat 系统展示 用户登录 首页 评审条件 论坛信息 系统公告 后台登录…

CTFshow-PWN-前置基础(pwn26-pwn31)

目录 1、pwn26 2、pwn27 3、pwn28 4、pwn29 5、pwn30 6、pwn31 1、pwn26 设置好 ASLR 保护参数值即可获得flag 首先我们需要知道什么是 ASLR&#xff1f; ASLR&#xff08;Address Space Layout Randomization&#xff09;是一种操作系统级别的安全功能&#xff0c;它通…