Java-根据HTTP链接读取文件转换为base64

1.方法调用 本地路径或http路径

java 复制代码
   public static String fileToBase64(String filePath) throws IOException {
        // 判断是否为URL
        if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
            byte[] bytes = downloadFileToByteArray(filePath);
            return Base64.getEncoder().encodeToString(bytes);
        } else {
            // 处理本地文件
            File file = new File(filePath);
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                byte[] bytes = new byte[(int) file.length()];
                fileInputStream.read(bytes);
                return Base64.getEncoder().encodeToString(bytes);
            }
        }
    }

2.请求http连接文件资源获取并存入缓存

java 复制代码
public static byte[] downloadFileToByteArray(String fileUrl) throws IOException {
        // 创建 URL 对象
        URL url = new URL(fileUrl);
        // 打开 HTTP 连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为 GET
        connection.setRequestMethod("GET");

        // 获取输入流
        BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
        // 创建字节数组输出流,用于存储从输入流读取的数据
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        // 定义缓冲区
        byte[] buffer = new byte[1024];
        int bytesRead;
        // 从输入流读取数据到缓冲区,并将缓冲区的数据写入输出流
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }

        // 关闭输入流和输出流
        in.close();
        out.close();

        // 断开 HTTP 连接
        connection.disconnect();

        // 将字节数组输出流中的数据转换为字节数组并返回
        return out.toByteArray();
    }
相关推荐
少控科技8 小时前
QT第6个程序 - 网页内容摘取
开发语言·qt
darkb1rd8 小时前
八、PHP SAPI与运行环境差异
开发语言·网络安全·php·webshell
南极企鹅8 小时前
springBoot项目有几个端口
java·spring boot·后端
历程里程碑8 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法
郝学胜-神的一滴8 小时前
深入浅出:使用Linux系统函数构建高性能TCP服务器
linux·服务器·开发语言·网络·c++·tcp/ip·程序人生
清风拂山岗 明月照大江8 小时前
Redis笔记汇总
java·redis·缓存
承渊政道8 小时前
Linux系统学习【Linux系统的进度条实现、版本控制器git和调试器gdb介绍】
linux·开发语言·笔记·git·学习·gitee
xiaoxue..8 小时前
合并两个升序链表 与 合并k个升序链表
java·javascript·数据结构·链表·面试
JQLvopkk9 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#
忧郁的Mr.Li9 小时前
SpringBoot中实现多数据源配置
java·spring boot·后端