领导要求将文章中添加的图片通过路径现在到自己的服务器下面并把路径替换成自己的服务器图片链接,第一篇文章,不知道说啥,直接上代码吧! *******皆为不可展示内容 请体谅
public class updateImg {
private static final String endpoint = "*********";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号
private static final String accessKeyId = "********";
private static final String accessKeySecret = "*********";
/*
*获取图片连接并判断是否为网址
*/
public String getImgStr(String count) throws Exception{
Pattern p = Pattern.compile("<(img|IMG)(.*?)(>|></img>|/>)");//匹配字符串中的img标签
Matcher matcher = p.matcher(count);
boolean hasPic = matcher.find();
if(hasPic == true){//判断是否含有图片
while(hasPic){ //如果含有图片,那么持续进行查找,直到匹配不到
String group = matcher.group();
Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
Matcher matcher2 = srcText.matcher(group);
//判断是否为域名,不是域名则下载到服务器
Pattern pattern = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
if( matcher2.find() == true && pattern.matcher(matcher2.group()).matches() == false)
{
URL url = new URL(matcher2.group().substring(5,matcher2.group().length()-1));//因为匹配出的路径是src="****"格式 所以通过截取来获取
String last = getUrl(String.valueOf(url));//有的链接后面会带有?的后缀,进行判断获取图片的格式
URLConnection con = url.openConnection();//打开链接
con.setConnectTimeout(120*1000);//设置时间
InputStream is = con.getInputStream();// 输入流
byte[] bs = new byte[1024];// 1K的数据缓冲
int len;// 读取到的数据长度
String xxUrl = "temp";//“temp”为项目下的路径,将图片先下载带项目下的路径保存
File sf=new File(xxUrl);//输出文件流
if(!sf.exists()){
sf.mkdirs();
}
String uuid32 = getUUID32();//随机生成32位随机数作为图片名称
OutputStream os = new FileOutputStream(sf.getPath()+"/"+uuid32+last);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
//将图片上传到服务器
URL xUrl = new URL("********"+"/2/");//xUrl为服务器保存图片路径
File file = new File(sf.getPath()+"/"+uuid32+last);//现在带本地的图片路径
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
PutObjectResult putObjectResult = ossClient.putObject("*****", "2/" + uuid32 + last, file);//上传到服务器指定目录中
os.close();//关流
is.close();//关流
ossClient.shutdown();//关流
this.deleteFile(file);//删除现在到项目目录下的图片
//替换图片url
String replaceHttp = xUrl+uuid32+last;//服务器图片地址
String countx = count.replaceAll(String.valueOf(url),replaceHttp);将文章中的src中的src路径替换
count = countx;//将替换后的文章赋值给原参
}
hasPic = matcher.find();//判断是否还有img标签
}
}
return count;//返回文章
}
/*
*生成随机32位数字
*/
public static String getUUID32() {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
return uuid;
}
/*
*删除文件
*/
private void deleteFile(File... files) {
File[] var2 = files;
int var3 = files.length;
for(int var4 = 0; var4 < var3; ++var4) {
File file = var2[var4];
if (file.exists()) {
file.delete();
}
}
}
/*
*判断链接是否带有?后缀
*/
public static String getUrl(String url) {
if (!String.valueOf(url).contains("?")) {
String last = url.substring(url.lastIndexOf("."));
return last;
}else{
String lastIndex = url.substring(0,url.indexOf("?"));
String last = lastIndex.substring(lastIndex.lastIndexOf("."));
return last;
}
}
}
OSS的配置文件
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency>
原始参数:
替换后的数据:
至此,整个过程全部完成,最后在将替换后的链接打开查看是否添加到服务器上,经验不足的小白菜,代码不够美观,请各位大佬见谅,此文章仅仅是个人记录,若能帮到各位也是荣幸之至。
参考文章:https://www.cnblogs.com/thinkingandworkinghard/articles/5589484.html