可能会有公告或者新闻的需求,而前段又没有直传阿里云,这个时候就需要替换内容中的base64 上传阿里云然后存储地址了
/**
* 将base64 上传 并替换
* @param html
* @return
*/
private String uploadBaseReplace(String html) {
if (StrUtil.isNotEmpty(html)) {
Set<String> imgStr = getImgStr(html);
for (String src : imgStr) {
if (src.contains("base64")){
try {
String imagePath = upload(src, "", snowflake.nextIdStr(), 0);
html.replace(src,Base64OSS.getUrl("", imagePath).toString());
} catch (Exception e) {
log.error("上传 阿里云失败,错误",e.getMessage());
}
}
}
}
return html;
}
public static String upload(String fileString, String dir, String fileName, int useType) throws Exception {
OSS ossClient = buildOssClient();
String suffix = "";
String prefix = "";
String key = "";
byte[] bytes = new byte[]{};
if (useType == 0) // 0- 为image内容
{
suffix = fileString.substring(11, fileString.indexOf(";"));
prefix = fileString.substring(0, fileString.indexOf(",") + 1);
fileString = fileString.replace(prefix, "");
bytes = Base64.getMimeDecoder().decode(fileString); //将字符串转换为byte数组,这里的content是那一串base64密文 /9j/4AAQ.................,不包含(data:img/jpg;base64,)注意标点符号
}
else if (useType == 1) // 1- 为 html 内容
{
suffix = "";
bytes = fileString.getBytes("utf-8"); //将字符串转换为byte数组,这里的content是那一串base64密文 /9j/4AAQ.................,不包含(data:img/jpg;base64,)注意标点符号
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(inputStream.available());
metadata.setCacheControl("no-cache");
// 指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
// 指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
if (Strings.isNullOrEmpty(dir)) {
dir = fileDir;
}
key = getFilename(dir, fileName, suffix);
ossClient.putObject(bucketName, key, inputStream,metadata);
URL url = getUrl(ossClient, key);
System.out.print(url);
ossClient.shutdown();
if (useType == 1){
//1- 为 html 内容
return url.toString();
}
return key;
}
/**
* 得到网页中图片的地址
* @param htmlStr html字符串
*/
public static Set<String> getImgStr(String htmlStr) {
Set<String> pics = new HashSet<String>();
String img = "";
Pattern p_image;
Matcher m_image;
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(htmlStr);
while (m_image.find()) {
// 得到<img />数据
img = m_image.group();
// 匹配<img>中的src数据
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
pics.add(m.group(1));
}
}
return pics;
}