SpringBoot整合FTP上传文件

  1. 添加pom依赖

        <dependency>
            <groupId>commons-netgroupId>
            <artifactId>commons-netartifactId>
            <version>3.6version>
        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;
    }
}

你可能感兴趣的:(Spring,Boot,文件存储,FTP文件存储,spring,boot)