springboot实现FTP服务器的上传和下载

在pom中添加以下依赖

 <!-- 这是ftp的jar包 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
 <!-- Slf4j -->
 		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency> 
   <!-- hutool工具包 -->
		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.0.9</version>
        </dependency>

添加配置文件

自行添加自己的配置

#ftp配置
#ftp服务器的ip地址
ftp.host=
#ftp服务器的端口号
ftp.port=
#ftp服务器的上传下载路径
ftp.filepath=/
#ftp服务器的用户名
ftp.username=Admin
#ftp服务器的密码
ftp.password=

FTPUtils工具类


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

@Component
@Data
@Slf4j
@Service
public class FTPUtils {
    public static final int imageCutSize = 300;

    @Value("${ftp.username}")		//用户名
    private String userName;

    @Value("${ftp.password}")		//密码
    private String passWord;

    @Value("${ftp.host}")			//ip地址
    private String ip;

    @Value("${ftp.port}")			//端口号
    private int port;

    @Value("${ftp.filepath}")
    private String CURRENT_DIR;     // 文件存放的目录

    public static final String DIRSPLIT = "/";


    private String DOWNLOAD_DIR;
    private FTPClient ftpClient = new FTPClient();
    //上传
    public boolean uploadToFtp(InputStream buffIn, String fileName, boolean needDelete)
            throws FTPConnectionClosedException, IOException, Exception {
        boolean returnValue = false;

        try {

            // 建立连接
            connectToServer();
            // 设置传输二进制文件
            setFileType(FTP.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new IOException("无法连接到FTP服务器:" + ip);
            }
            /*ftpClient.enterLocalPassiveMode();*/
            //进入文件目录
            ftpClient.changeWorkingDirectory(CURRENT_DIR);
            // 上传文件到ftp
            returnValue = ftpClient.storeFile(fileName, buffIn);
            if (needDelete) {
                ftpClient.deleteFile(fileName);
            }
            // 输出操作结果信息
            if (returnValue) {
                System.out.println("uploadToFtp INFO: 将文件上传到ftp:成功!");
            } else {
                System.out.println("uploadToFtp INFO: 将文件上传到ftp:失败!");
            }
            buffIn.close();
            // 关闭连接
            closeConnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println("ftp连接被关闭!");
            throw e;
        } catch (Exception e) {
            returnValue = false;
            System.out.println("ERR : 将文件上传到ftp:失败! ");
            throw e;
        } finally {
            try {
                if (buffIn != null) {
                    buffIn.close();
                }
            } catch (Exception e) {
                System.out.println("ftp关闭输入流时失败!");
            }
            if (ftpClient.isConnected()) {
                closeConnect();
            }
        }
        return returnValue;
    }




//下载
    public InputStream downloadFile(String filename)
            throws IOException {
        InputStream in = null;
        try {

            // 建立连接
            connectToServer();
            ftpClient.enterLocalPassiveMode();
            // 设置传输二进制文件
            setFileType(FTP.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                throw new IOException("无法连接到FTP服务器:" + ip);
            }
            ftpClient.changeWorkingDirectory(CURRENT_DIR);

            // ftp文件获取文件
            in = ftpClient.retrieveFileStream(filename);

        } catch (FTPConnectionClosedException e) {
            System.out.println("ftp连接被关闭!");
            throw e;
        } catch (Exception e) {
            System.out.println("ERR : 从ftp下载文件 " + filename + " 失败");

        }
        System.out.println("download file INFO: 将文件下载到本地:成功!");
        return in;
    }

    private void setFileType(int fileType) {
        try {
            ftpClient.setFileType(fileType);
        } catch (Exception e) {
            System.out.println("ftp设置传输文件的类型时失败!");

        }
    }

    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            System.out.println("ftp连接关闭失败!");

        }
    }

    private void connectToServer() throws FTPConnectionClosedException, Exception {
        if (!ftpClient.isConnected()) {
            int reply;
            try {
                ftpClient = new FTPClient();
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.enterLocalPassiveMode();
                ftpClient.connect(ip, port);
                ftpClient.login(userName, passWord);
                reply = ftpClient.getReplyCode();

                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    System.out.println("connectToServer FTP服务器拒绝连接。");

                }

            } catch (FTPConnectionClosedException ex) {
                System.out.println("没有连接数!连接的用户太多,请稍后再试");

                throw ex;
            } catch (Exception e) {
                System.out.println("登录ftp服务器失败");
                throw e;
            }
        }
    }

    // 检查路径是否存在; 存在返回true,否则返回false。
//    public boolean existDirectory(String path) throws IOException {
//        boolean flag = false;
//        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
//        for (FTPFile ftpFile : ftpFileArr) {
//            if (ftpFile.isDirectory()
//                    && ftpFile.getName().equalsIgnoreCase(path)) {
//                flag = true;
//                break;
//            }
//        }
//        return flag;
//    }
//
//    public boolean createDirectory(String pathName) throws IOException {
//        boolean isSuccess = false;
//        try {
//            isSuccess = ftpClient.makeDirectory(pathName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return isSuccess;
//    }
//
//    public static String getExtention(String fileName) {
//        int pos = fileName.lastIndexOf(".");
//        return fileName.substring(pos);
//    }
//
//    public static String getNoPointExtention(String fileName) {
//        int pos = fileName.lastIndexOf(".");
//        return fileName.substring(pos + 1);
//    }
//
//    public static String getDateDir(Date dateParam) {
//        Calendar cal = Calendar.getInstance();
//        if (null != dateParam) {
//            cal.setTime(dateParam);
//        }
//        int currentYear = cal.get(Calendar.YEAR);
//        int currentMouth = cal.get(Calendar.MONTH) + 1;
//        int currentDay = cal.get(Calendar.DAY_OF_MONTH);
//        //int currentHour = cal.get(Calendar.HOUR_OF_DAY);
//        //return currentYear+FtpOperation.DIRSPLIT+currentMouth+FtpOperation.DIRSPLIT+currentDay+FtpOperation.DIRSPLIT+currentHour;
//        return currentYear + FTPUtils.DIRSPLIT + currentMouth + FTPUtils.DIRSPLIT + currentDay;
//    }
}


Controller

package com.example.demo01.controller;

import cn.hutool.core.io.FileUtil;
import com.example.demo01.utils.FTPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.InputStream;

@Controller
public class FTPController {

    @Autowired
    private FTPUtils ftpUtils;
    @RequestMapping("/uploadToFtp")
    public String uploadToFtp() {
        File file = new File("D:\\skills1.txt");
        InputStream inputStream = FileUtil.getInputStream(file);
        try {
            ftpUtils.uploadToFtp(inputStream, "skills3.txt", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    @RequestMapping("/downloadFile")
    public String downloadFile() {
        try {
            InputStream inputStream = ftpUtils.downloadFile("skills.txt");
            FileUtil.writeFromStream(inputStream, "E:\\skills.txt");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值