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();
    }
相关推荐
Wang's Blog几秒前
Java框架 SpringCloud 快速入门: 网关的 CORS 跨域配置
java·开发语言·spring cloud
驭渊的小故事4 分钟前
NC229023 题解:二分答案求解“最大化最小值“问题
java·算法
小贺儿开发6 分钟前
Unity 局域网遥控幻灯片展示工具 3.0
科技·http·unity·工具·ppt·通信·网页
小蒜学长8 分钟前
基于SSM+VUE的电影售票平台的设计与实现(代码+数据库+LW)
java·vue.js·spring boot·后端·ssm框架·电影售票平台
code2cat8 分钟前
【随笔】MCP工具错误怎样分层:先读反馈,再决定下一步
开发语言·后端·ai agent·mcp
朝朝辞暮i17 分钟前
C++ 第 36 课:Action——机械臂/VLA 非常重要
开发语言·c++·算法·ros2
谢亮_vipxieliang20 分钟前
Go 接口设计原则核心知识点
开发语言·ios·golang
Wang's Blog21 分钟前
Java框架 SpringCloud 快速入门: Feign 替代 RestTemplate 实现声明式远程调用
java·开发语言·spring cloud
谢亮_vipxieliang22 分钟前
Go 结构体与方法集核心知识点
java·开发语言·golang
郝学胜-神的一滴24 分钟前
Numpy数据处理详解 01:NumPy 从环境搭建到入门上手
开发语言·人工智能·python·程序人生·数据分析·numpy