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();
    }
相关推荐
考虑考虑1 小时前
JDK25模块导入声明
java·后端·java ee
_小马快跑_2 小时前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
Re_zero5 小时前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记5 小时前
Spring Boot条件注解详解
java·spring boot
程序员清风1 天前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5511 天前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
华仔啊1 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing1 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot