FTP服务器上传文件-Java实战

properties配置文件设置:

host=ip
port=21
username=root
password=root

配置文件获取:

InputStream inputStream = FtpUploadUtil.class.getClassLoader()
                .getResourceAsStream("uploadfile.properties");
Properties properties = new Properties();
properties.load(inputStream);
Map<String, String> parmMap = new HashMap<String, String>();
parmMap.put("host", properties.getProperty("host"));
parmMap.put("port", properties.getProperty("port"));
parmMap.put("username", properties.getProperty("username"));
parmMap.put("password", properties.getProperty("password"));

1.获取线上文件url

url为下载路径  filePath为存储到本地的文件路径

public static File getFile(String url, String filePath) {
        File file = null;
        URL urlfile;
        try {
            // 创建一个临时路径
            file = new File(filePath);
            //下载
            urlfile = new URL(url);
            try{
                InputStream inStream = urlfile .openStream();
                OutputStream os =  new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                inStream.close();
            }catch (IOException e) {
                Logger.error("创建失败!");
            }
        } catch (Exception e) {
            Logger.error("创建临时文件出错:-》{}"+e.getMessage());
        }
        return file;
    }

也可直接将本地文件上传至FTP服务器中,当然实际项目业务场景多为获取线上文件

2、文件上传至FTP服务器

destPath为服务器文件夹路径,如没有会自动创建

public void ftpUploadFile(Map<String, String> parm,String uploadFilePath,String destPath) throws BusinessException{
        String hostname = parm.get("host");
        int port = new Integer(parm.get("port"));
        String username = parm.get("username");
        String password = parm.get("password");
        FTPClient ftp = new FTPClient();
        Logger.info("准备连接到ftp");
        try {
            //连接
            ftp.connect(hostname, port);
            //登录
            boolean loginS = ftp.login(username, password);
            if (!loginS) {
                throw new BusinessException("ftp登录失败,用户名或密码错误");
            }else{
                Logger.info("ftp登录成功");
            }

            // 获取本地文件并上传
            String file = uploadFilePath;
            FileInputStream input = new FileInputStream(file);
            //切换到工作目录
            if (!ftp.changeWorkingDirectory(destPath)) {
               ftp.changeWorkingDirectory("/");
               String[] dirs = destPath.split("/");
               for (String dir : dirs) {
                  ftp.makeDirectory(dir);
                  ftp.changeWorkingDirectory(dir);
               }
            }
            //必须要设置以二进制的方式传输文件
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //被动模式
            ftp.enterLocalPassiveMode();
            file = new String(file.getBytes("GBK"),"iso-8859-1");
            if (!ftp.storeFile(new File(file).getName(), input)) {
                throw new BusinessException("失败,服务器返回:" + ftp.getReplyString());
            } else {
                Logger.info("文件:" + new File(file).getName() + " 上传成功");
            }
            input.close();
            ftp.logout();
        } catch (IOException e) {
            ExceptionUtils.wrappException(e);
        }
    }

3、测试demo

String filepath = "localpath"; String destpath = "file/0810";
String downurl = "https://trustedsign.com/kxqtest/common/download/MNBCLKYBUNTEOYYK";
File file = getFile(downurl,filepath);
ftpUploadFile(host,port,username,password,file.getPath(),destpath);

4、总结

该案例是项目过程中遇到的,比较有参考意义,如有疑问请及时留言,多多交流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值