直接上代码–工具类
/**
* 对富文本base64图片进行转换上传处理
* @param content
* @return
* @throws Exception
*/
public String handlerBase64Content(String content) throws Exception{
if(StringUtil.isNotEmpty(content)){
//获取src值
List<String> srcvalues=getImgSrc(content);
String temp=null;
for(String src:srcvalues){
if(src.startsWith("data:image/")){
temp=uploadBase64File(src);
content=content.replace(src,temp);
}
// else if(src.contains(parentName)){
// temp=src.substring(src.indexOf(parentName));
// content=content.replace(src,temp);
// }
else{
//其他的属于网络图片,不用处理
//返回图片地址
}
}
}
return content;
}
/**
* 获取文本中的img标签的src属性值
* @param htmlStr
* @return
*/
public static List<String> getImgSrc(String htmlStr) {
String img = "";
Pattern p_image;
Matcher m_image;
List<String> pics = new ArrayList<String>();
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();
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
pics.add(m.group(1));
}
}
return pics;
}
/**
* 上传base64位的图片
* @param imgStr
* @throws Exception
*/
private String uploadBase64File(String imgStr) throws Exception{
InputStream is = GenerateImage(imgStr);
File file=stream2file(is);
String fileUrl=uploadFile(file);
File files=new File(file.getPath());
if(files.exists()) files.delete();
return fileUrl;
}
//base64字符串转化成图片
private InputStream GenerateImage(String imgStr) throws Exception{
String newfilename= UUID.randomUUID().toString()+"";
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
imgStr=imgStr.substring(imgStr.indexOf("base64,")+7);
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
InputStream inputStream = new ByteArrayInputStream(b);
return inputStream;
}
/**
* 上传文件
* @param file
* @return
* @throws Exception
*/
private String uploadFile(File file){
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentLength(file.length());
MultiValueMap<String, Object> forms = new LinkedMultiValueMap<>();
forms.add("multipartFile", new FileSystemResource(file));
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(forms, headers);
String data=restTemplate.postForObject("https://xxx.com/xxx/upload",httpEntity,String.class);
if(StringUtils.isNotEmpty(data)){
return data;
}else{
return null;
}
}
实现层直接引用
下面展示一些 内联代码片
。
//举例context为富文本内容 该方法会直接对IMG内容中 base64字符串转成oss文件路径
public ResultData<String> getUrl(String context) throws Exception {
String url=appTokenUtils.handlerBase64Content(context);
return ResultFactory.okResponse(url);
}
减少数据库负担