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();
    }
相关推荐
feixing_fx16 分钟前
第一个 JS 程序:在浏览器控制台和 Node 中分别运行
开发语言·前端·javascript·前端框架·ecmascript
Evand J1 小时前
【MATLAB例程】二维IMM-UKF定位,基于四个基站的AOA与测距辅助
开发语言·matlab
feixing_fx1 小时前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
个 人 练 习 生2 小时前
C++:从零基础到深入了解vector的使用
开发语言·c++·经验分享·学习·程序人生·stl
兴趣互联3 小时前
jeecgboot nacos2.3.2 使用pgsql
java
H.莓飛3 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
hudd6683 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
Flynn Liang4 小时前
HikariCP 连接池不是越大越好:I/O 密集型 Java 服务的数据库容量工程
java·数据库·mysql·高并发·连接池·hikaricp·sql 优化
学长毕设4 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端
starzy19904 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala