当前位置:网站首页>在线文件不落地转base64

在线文件不落地转base64

2022-06-11 10:31:00 差点资深程序员

/**
     * 文件链接转base64
     * @param urlStr 文件在线url
     * @return 文件base64格式
     */
    public static String fileToBase64(String urlStr){
        String base64 = null;
        try {
            // 统一资源
            URL url = new URL(urlStr);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();
            // 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
            // 建立链接从请求中获取数据
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len;
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            while ((len = bin.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            bin.close();
            byte[] bytes = outStream.toByteArray();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            System.out.println("base64" + base64Encoder.encode(bytes));
            bin.close();
            base64 = base64Encoder.encode(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64;
    }

原网站

版权声明
本文为[差点资深程序员]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44307338/article/details/125204943