java通过文件的url获取文件的base64

java通过文件的url获取文件的base64

package org.Util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

/**
 * @author Hmoumou
 * @DATE 2022/1/3
 * @apiNote
 * 通过文件的url链接
 * 获取文件的base64
 */
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description 文件转base64
 */
class Base64Util {

    /**
     * 文件转base64
     *  直接返回base64结果
     * @param
     * @return
     */
    public static String encryptToBase64(String urlString) throws IOException {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5 * 1000);
        // 输入流
        InputStream is = con.getInputStream();
        // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(data);
    }

    public static void main(String[] args) throws Exception {
        for (int i = 1; i < 10; i++) {
            String url = "https://smartdl.lenovo.com.cn/frontend/browser/hao.edge/image/af4616c312d.png";
            String dd = encryptToBase64(url);
            System.out.println(dd);
            System.out.println("---------------------------------------");
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值