查找ftp上的文件,并将文件转换为base64文件流返回

该段代码展示了如何使用FTPClient连接服务器,下载指定文件并将其内容转化为Base64编码。首先检查BDCDYH是否为空,然后通过mapper获取文件名,连接FTP服务器并登录。设置文件类型为二进制,判断登录状态,读取文件内容并转换为字节数组,最后使用Base64编码器将字节数组编码为字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if (StringUtils.isBlank(bdcdyh)) {
    throw new ServiceRuntimeException("bdcdyh is null");
}
String fileName = signApprovedMapper.selectDzht(bdcdyh);
FTPClient ftpClient = new FTPClient();
String re = null;
InputStream inputStream = null;
try {
    ftpClient.connect(ftpHost, ftpPort);//ip地址,端口号
    ftpClient.login(user, password);//账户,密码
    ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    //是否成功登录服务器
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
    }

    inputStream = ftpClient.retrieveFileStream(fileName);


    if (inputStream != null) {
        byte[] data = null;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        data = new byte[inputStream.available()];
        int len = 0;
        while ((len = inputStream.read(data)) != -1) {
            outStream.write(data, 0, len);
        }
        data = outStream.toByteArray();
        Base64.Encoder encoder = Base64.getEncoder();
        re = encoder.encodeToString(data);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (ftpClient.isConnected()) {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (null != inputStream) {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
return re;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值