引入坐标
<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);
}