Springboot连接Ftp服务器实现文件上传下载

本地测试时,首先在本地部署一个ftp服务器,参考以下

在本机搭建自己的ftp服务器--最简单的方法(详细教程)_ftp服务器怎么搭建_路baby的博客-CSDN博客

其中的第三步,注意要将”万维网服务“一并选上,否则会在后续为ftp服务器添加用户密码的时候报错

 在给ftp服务器设置用户名密码的时候,需要有一个本地用户,如何新增参考以下

百度安全验证

最后进行给ftp服务器设置用户名密码的操作,参考以下

win10 FTP服务器设置用户名和密码_feifei_Tang的博客-CSDN博客_win10ftp服务器设置用户名和密码

以上,设置一个ftp服务完成。

依赖:

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

工具类:

@Component
public class UploadFileUtil {
    @Autowired
    public FTPUtil ftpUtil;

    public String uploadFileToFtp(MultipartFile[] fileList) throws Exception {

        //1、获取原文件后缀名
        MultipartFile multipartFile = fileList[0];
        String originalFileName = multipartFile.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf('.'));

        //2、使用UUID生成新文件名
        String newFileName = UUID.randomUUID() + suffix;

        //3、将MultipartFile转化为File
        File file = this.multipartFileToFile(multipartFile);

        //4、上传至ftp服务器
        if (ftpUtil.uploadToFtp("/", newFileName, file)) {
            System.out.println("上传至ftp服务器!");
        } else {
            System.out.println("上传至ftp服务器失败!");
        }
        return "上传成功";
    }
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Data
@Slf4j
@Service
public class FTPUtil {

    @Value("${ftp_ip}")
    private String ftpIp;
    @Value("${ftp_port}")
    private Integer ftpPort;
    @Value("${ftp_user}")
    private String ftpUser;
    @Value("${ftp_pass}")
    private String ftpPass;

    private FTPClient ftpClient;

    private boolean connectServer(String ip,int port,String user,String pwd){
        ftpClient=new FTPClient();
        Boolean isSuccess=false;
        try {
            ftpClient.connect(ip);
            isSuccess=ftpClient.login(user,pwd);
        } catch (IOException e) {
            log.error("连接ftp服务器失败",e);
        }
        return isSuccess;
    }

    public boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
        boolean upload=true;
        FileInputStream fileInputStream=null;
        //connect to ftpServer
        if (connectServer(ftpIp,ftpPort,ftpUser,ftpPass)){
            try {
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                for (File fileItem:fileList
                ) {
                    fileInputStream=new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(),fileInputStream);
                }
            } catch (IOException e) {
                log.error("上传文件异常",e);
                upload=false;
            }finally {
                if (fileInputStream!=null)fileInputStream.close();
                ftpClient.disconnect();
            }
        }
        return upload;
    }

    public boolean uploadToFtp(String remotePath, String fileName, File file) throws IOException {
        boolean upload = true;
        FileInputStream fileInputStream = null;
        //connect to ftpServer
        if (connectServer(ftpIp, ftpPort, ftpUser, ftpPass)) {
            try {
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();

                //上传文件 参数:上传后的文件名,输入流
                upload = ftpClient.storeFile(fileName, new FileInputStream(file));
            } catch (IOException e) {
                log.error("上传文件异常", e);
                upload = false;
            } finally {
                if (fileInputStream!=null)fileInputStream.close();                ftpClient.disconnect();
            }
        }
        return upload;
    }

    //下载
public boolean download() throws Exception {
        if (connectServer(ftpIp, ftpPort, ftpUser, ftpPass)){
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                // 本地文件路径
                File f = new File("D:\\crmFiles\\");
                if (!f.exists()) {
                    f.mkdirs();
                }
                long lRemoteSize = file.getSize();
                try {// 下载过的不在下载了
                    OutputStream out = new FileOutputStream(f.getAbsoluteFile()+"//"+file.getName());
                    if (f.length() >= lRemoteSize) {
                        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~本地已经存在,下载中止");
                        out.flush();
                        out.close();
                    }
                    //下载
                    boolean iss = ftpClient.retrieveFile(file.getName(), out);
                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~下载成功\r\n");
                    out.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~下载失败\r\n");
                    return false;
                }
            }
        }
        return false;
    }
}

配置文件需要添加

ftp_ip=ftp服务器地址
ftp_port=ftp服务器端口号
ftp_user=ftp服务器用户名
ftp_pass=ftp服务器密码

调用:

@Autowired
public UploadFileUtil uploadFileUtil;

@GetMapping("test")
public String test(MultipartFile[] file) throws Exception {
    return uploadFileUtil.uploadFileToFtp(file);
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值