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();
    }
相关推荐
bkspiderx2 小时前
用Nginx解决HTTP跨域问题:两种实用方案详解
nginx·http·跨域·http跨域
AC赳赳老秦2 小时前
CSV大文件处理全流程:数据清洗、去重与格式标准化深度实践
大数据·开发语言·人工智能·python·算法·机器学习·deepseek
YIN_尹2 小时前
CANN开源仓Catlass模板库核心能力与编程实战
java·开源·dubbo
华如锦2 小时前
微调—— LlamaFactory工具:使用WebUI微调
java·人工智能·python·ai
2501_930707782 小时前
如何使用C#代码将 Excel 文件转换为 SVG
开发语言·c#·excel
程序员修心2 小时前
CSS 盒子模型与布局核心知识点总结
开发语言·前端·javascript
C语言小火车2 小时前
【C++】从零开始构建C++停车场管理系统:技术详解与实战指南
开发语言·c++·毕业设计·课程设计
亚历山大海2 小时前
PHP发送outlook(微软)OAuth 2.0企业版邮箱验证码
开发语言·php·outlook
武子康2 小时前
Java-215 RocketMQ 消费模式:Push vs Pull 的本质、长轮询机制与 Offset/积压调优要
java·大数据·分布式·消息队列·rocketmq·java-rocketmq·mq