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();
    }
相关推荐
chushiyunen4 分钟前
python中的内置属性 todo
开发语言·javascript·python
麦麦鸡腿堡8 分钟前
JavaWeb_请求参数,设置响应数据,分层解耦
java·开发语言·前端
2301_8194143031 分钟前
C++与区块链智能合约
开发语言·c++·算法
不想看见40438 分钟前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
炸膛坦客41 分钟前
单片机/C/C++八股:(十五)内存对齐、结构体内存对齐
c语言·开发语言·单片机
娇娇yyyyyy1 小时前
QT编程(13): Qt 事件机制eventfilter
开发语言·qt
bcbobo21cn1 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型
计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
阿贵---1 小时前
C++构建缓存加速
开发语言·c++·算法
没有bug.的程序员1 小时前
Serverless 弹性扩容引发的全线熔断:Spring Boot 启动耗时从 1s 压缩至 0.3s 的物理级绞杀
java·spring boot·kubernetes·serverless·扩容·线上