springboot集成ftp文件上传

一、导入 ftp 依赖文件

<!-- 导入ftp的依赖 -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

二、配置 yml 文件

ftp:
  #ip
  hostname: xx.xxx.xxx.xxx
  #端口
  port: 21
  #用户名
  username: ftpadmin
  #密码
  password: ftpadmin
  #存储的位置
  save-path: /home/ftptest/ftp

三、创建 FtpConfig

@Data
@Component
@ConfigurationProperties(prefix = "ftp")
public class FtpConfig {
    private String hostname; // ip
    private int port; // 端口
    private String username; // 账号
    private String password; // 密码
    private String savePath; // 存储的位置
}

四、创建 FtpUtil

@Slf4j
@Component
public class FtpUtil {
​
    @Autowired
    private FtpConfig reFtpConfig;
​
    private static FtpConfig ftpConfig;
​
    @PostConstruct
    public  void init() {
        ftpConfig = reFtpConfig;
        log.info("初始化完成");
    }
​
    // 连接ftp
    public static FTPClient getConnection() {
        FTPClient ftpClient = new FTPClient();
        try {
            // 设置连接机器
            ftpClient.connect(ftpConfig.getHostname(), ftpConfig.getPort());
            ftpClient.login(ftpConfig.getUsername(), ftpConfig.getPassword());
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("ftp连接失败");
                ftpClient.disconnect(); // 断开连接
                return null;
            } else {
                log.info("ftp连接成功");
            }
​
            // 将文件类型设置成二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 创建要存储文件夹的目录: 主要目录只能一级一级创建,不能一次创建多层; 在 选择创建目录是一定要看是否有写权限,不然失败
            ftpClient.makeDirectory(ftpConfig.getSavePath());
            // 改变默认存放的位置
            ftpClient.changeWorkingDirectory(ftpConfig.getSavePath());
            //开启被动模式,否则文件上传不成功,也不报错
            ftpClient.enterLocalPassiveMode();
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
        return ftpClient;
    }
​
​
    // 上传文件
    public static void uploadFile(String fileName, InputStream inputStream) {
​
        FTPClient ftpClient = getConnection();
        if (ftpClient == null) {
            return;
        }
        try {
            boolean result = ftpClient.storeFile(fileName, inputStream);
            log.info("文件是否保存成功:" + result);
            inputStream.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
    // 文件下载
​
    /**
     *
     * @param fileName
     * @param localPath  不指定表示下载到当前项目下
     */
    public static void downloadFile( String localPath, String fileName) {
        FTPClient ftpClient = getConnection();
        if (ftpClient == null) {
            return;
        }
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (fileName.equals(ftpFile.getName())) {
                    File file = new File(localPath+fileName);
                    OutputStream outputStream = new FileOutputStream(file);
                    boolean result = ftpClient.retrieveFile(ftpFile.getName(), outputStream);
                    log.info("下载结果:" + result);
                    outputStream.close();
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }
​
    }
}

五、创建 FtpController

@RestController
@RequestMapping("/ftp")
public class FtpController {
​
    @Autowired
    private FtpConfig ftpConfig;
​
    // 文件上传
    @PostMapping("/upload")
    public String upload(@RequestPart("file") MultipartFile [] file) throws IOException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 单文件上传:通过ftp封装的工具类,将文件传递到指定的文件服务器
        for (MultipartFile multipartFile : file) {
            InputStream inputStream = multipartFile.getInputStream();
            String filename = multipartFile.getOriginalFilename();
            FtpUtil.uploadFile(filename,inputStream);
        }
        stopWatch.stop();
        System.out.println("共耗时:"+stopWatch.getTotalTimeMillis()+"ms");
        return "seccess";
    }
​
​
    // 文件下载
    @GetMapping("/download")
    public String download(String fileName) {
        FtpUtil.downloadFile(ftpConfig.getSavePath() , fileName);
        return "success";
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值