当前位置: 首页 > 工具软件 > Base > 使用案例 >

Base64码常见操作(url链接文件转base64编码、本地文件转base64编码等)

赫连越
2023-12-01

引入坐标

		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.4.3</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.10</version>
		</dependency>

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

常见操作

下载远程url的文件并转换成base64编码

代码如下:

	public static String file(String url){
		String encode = null;
		try {
			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			CloseableHttpResponse response = client.execute(get);
			//文件流
			HttpEntity httpEntity = response.getEntity();
			InputStream inStream = httpEntity.getContent();
			byte[] bytes = IOUtils.toByteArray(inStream);
			//附件base64
			encode = cn.hutool.core.codec.Base64.encode(bytes);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return encode;
	}

测试:

    /**
     * 测试下载远程url的文件,转换成base64编码
     * @throws Exception
     */
    @Test
    public void testUrlFileToBase64() throws Exception {
        String BASE64Str = Base64Util.file("https://xxx.oss-cn-hangzhou.aliyuncs.com/upload/20220513/165242342M");
        System.out.println("BASE64Str:"+BASE64Str);
    }

因为是图片,可以复制输出的base64编码到这个网址验证:https://tool.jisuapi.com/base642pic.html
其他base64操作如下:

文件转base64编码

	public static String fileToBase64(File file) {
		try {
			byte[] imageData = FileUtils.readFileToByteArray(file);
			String base64 = encodeImage(imageData);
			return base64;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
	}


	public static String encodeImage(byte[] imageData) {
		String encodeStr = Base64.getEncoder().encodeToString(imageData);
		log.info("encodeImage>>" + encodeStr);
		return encodeStr;
	}

判断一个字符串是否是base64

	public static boolean isBase64(String str) {
		String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
		return Pattern.matches(base64Pattern, str);
	}

其他base64转换可以查看我这篇文章:Base64和byte[]数组互转的两种方式

 类似资料: