SpringBoot整合FTP上传文件

  1. 添加pom依赖
<!-- 这是ftp的jar包 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
  1. 编写服务配置
ftp:
  url: 1.xxx.xxx.18
  port: 21
  user: ftp
  password: ftp
  remoteFilePath: /ftp/
  1. 编写ftp工具类FtpUtils.java
package cn.sh.ideal.utils;

import java.io.BufferedInputStream;
import java.io.IOException;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpProtocolException;

@Component
@Slf4j
public class FtpUtils implements InitializingBean{
    private static FTPClient ftpClient = null;
    @Value("${ftp.url}")
    private String ftpUrl;
    @Value("${ftp.port}")
    private int ftpPort;
    @Value("${ftp.user}")
    private String ftpUser;
    @Value("${ftp.password}")
    private String ftpPassword;

    private static String url;
    private static int port;
    private static String user;
    private static String password;

    @Override
    public void afterPropertiesSet() throws Exception {
        url=ftpUrl;
        port=ftpPort;
        user=ftpUser;
        password=ftpPassword;
    }

    public static boolean uploadFTP(MultipartFile file, String filePath, String filename) {
        boolean tmp = true;
        // 上传FTP
        tmp = uploadFile(file, filePath, filename);

        return tmp;
    }

    public static boolean uploadFile(MultipartFile file, String filePath, String filename) {

        TelnetOutputStream to = null;
        BufferedInputStream inStream = null;
        boolean success = false;
        //filePath = remoteFilePath + filePath;
        try {
            if (file != null) {
                connectFTP();
                boolean tmp2 = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));// 改变工作路径
                log.info("FTP文件上传判断文件夹是否存在" + tmp2);
                if (!tmp2) {
                    createDir(filePath.replace("\\", "/"));
                    boolean b = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));
                    log.info("新建文件夹后,切换目录是否成功:{}",b);
                }

                inStream = new BufferedInputStream(file.getInputStream());
                success = ftpClient.storeFile(filename, inStream);
                if (success == true) {
                    return success;
                }
            }
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (to != null) {
                try {
                    to.flush();
                    to.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            closeFTP();
        }
    }

    public static boolean upload(MultipartFile file, String filePath, String fileName) throws FtpProtocolException {
        boolean flag;
        if(null != file){
            connectFTP();
            try {
                // 判断上传文件夹是否存在
                flag = ftpClient.changeWorkingDirectory(filePath);
                if(flag){
                    createDir(filePath.replace("\\", "/"));
                    // 创建目录后是否成功
                    boolean directory = ftpClient.changeWorkingDirectory(filePath.replace("\\", "/"));
                    log.info("创建目录后是否切换成功:{}", directory);

                }
                BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
                flag = ftpClient.storeFile(filePath, inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 创建文件夹
     *
     * @param
     * @param
     * @throws Exception
     */

    public static void createDir(String dirname) {
        try {
            boolean b = ftpClient.makeDirectory(dirname);
            log.info("是否在目标服务器上成功建立了文件夹: " + dirname + ","+b);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    /**
     * 建立FTP链接
     *
     * @throws FtpProtocolException
     */
    private static void connectFTP() throws FtpProtocolException {
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(url, port);
            // 获取响应码用于验证是否连接成功
            int reply = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                ftpClient.setControlEncoding("UTF-8");
                // 登录服务器
                ftpClient.login(user, password);
                ftpClient.enterLocalPassiveMode();//被动模式
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.setBufferSize(1024 * 1024 * 10);
                ftpClient.setDataTimeout(30 * 1000);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭FTP链接
     */
    public static void closeFTP() {
        try {
            // 退出FTP服务器
            boolean reuslt = ftpClient.logout();
            if (reuslt) {
                System.out.println("成功退出服务器");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭FTP服务器的连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("关闭FTP服务器的连接异常!");
            }
        }
    }
}

  1. 编写上传接口 FtpController.java
package cn.sh.ideal.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.sh.ideal.utils.FtpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * FTP文件上传
 */

@RestController
@RequiredArgsConstructor
@Api(tags = "ftp文件上传")
@RequestMapping("/ftp")
@Slf4j
public class FtpController {

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

    private static final Logger logger = LoggerFactory.getLogger(FtpController.class);
    SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMdd");

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "文件上传接口", notes = "文件上传接口")
    public String upload(@RequestParam("file_data")MultipartFile file) {

        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())).toLowerCase();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
        String dateStr = sdf.format(new Date());
        // 获取文件的后缀名
        int i = fileName.lastIndexOf(".");
        String newFilename = dateStr + fileName.substring(i);
        logger.info("newFileName:"+newFilename);
        String fileNewPath =sdf2.format(new Date());
        String pathStr =  remoteFilePath + fileNewPath;
        logger.info("文件上传文件夹路径"+pathStr);

        boolean tmp = false;
        try{
            tmp = FtpUtils.uploadFTP(file, pathStr, newFilename);
            logger.info("文件上传结果:"+tmp);
        }catch (Exception e){
            e.printStackTrace();
            return new String("文件上传异常");
        }
        if(!tmp){
            return new String("文件上传失败");
        }
        String filepath =pathStr+newFilename;
                logger.info("返回到页面的文件FTP路径"+filepath);
                return filepath;
    }
}
springboot整合ftp可以通过引入相关的依赖和配置来实现。首先,在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> ``` 然后,在application.properties或application.yml文件中配置ftp连接信息,例如: ``` ftp.host=ftp.example.com ftp.port=21 ftp.username=admin ftp.password=123456 ``` 接下来,创建一个FTP工具类,用于连接和操作ftp服务器。在该类中,可以使用`FTPClient`类进行ftp操作,例如上传文件、下载文件等。示例如下: ```java import org.apache.commons.net.ftp.FTPClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class FTPUtil { @Value("${ftp.host}") private String host; @Value("${ftp.port}") private int port; @Value("${ftp.username}") private String username; @Value("${ftp.password}") private String password; public void uploadFile(String remotePath, String fileName, File file) throws IOException { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(remotePath); try (InputStream inputStream = new FileInputStream(file)) { ftpClient.storeFile(fileName, inputStream); } } finally { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } } // 其他ftp操作方法... } ``` 最后,可以在其他地方注入`FTPUtil`类,并调用其方法来实现ftp操作。例如: ```java @Service public class MyService { private final FTPUtil ftpUtil; @Autowired public MyService(FTPUtil ftpUtil) { this.ftpUtil = ftpUtil; } public void uploadFile() { // 上传文件 File file = new File("path/to/file"); try { ftpUtil.uploadFile("remote/path", "filename.txt", file); } catch (IOException e) { e.printStackTrace(); } } // 其他方法... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值