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

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

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

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

Springboot连接Ftp服务器实现文件上传下载_第1张图片

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

百度安全验证

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

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

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

依赖:


    commons-net
    commons-net
    3.6

工具类:

@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 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);
}

你可能感兴趣的:(服务器,网络,运维)