java通过获取img标签里面的是src路径下载图片上传到指定服务器上并替换src路径

   领导要求将文章中添加的图片通过路径现在到自己的服务器下面并把路径替换成自己的服务器图片链接,第一篇文章,不知道说啥,直接上代码吧!  *******皆为不可展示内容  请体谅

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();
                if (group.contains("data-src")== true) {
                    String src = group.substring(group.lastIndexOf("src"));
                    Pattern srcText = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
                    Pattern srcText2 = Pattern.compile("(data-src|DATA-SRC)=(\"|\')(.*?)(\"|\')");//匹配图片的地址
                    Matcher matcher2 = srcText2.matcher(group);
                    Matcher matcher3 = srcText.matcher(src);
                    //判断是否为域名,不是域名则下载到服务器
                    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 && matcher3.find() == true) {
                        URL url = new URL(matcher2.group().substring(10, matcher2.group().length() - 1));
                        URL url1 = new URL(matcher3.group().substring(5, matcher3.group().length() - 1));
                        String last = getUrl(String.valueOf(url));
                        URLConnection con = url.openConnection();
                        con.setConnectTimeout(120 * 1000);
                        InputStream is = con.getInputStream();
                        byte[] bs = new byte[1024];
                        int len;
                        String xxUrl = "temp";
                        File sf = new File(xxUrl);
                        if (!sf.exists()) {
                            sf.mkdirs();
                        }
                        String uuid32 = getUUID32();
                        OutputStream os = new FileOutputStream(sf.getPath() + "/" + uuid32 + last);
                        // 开始读取
                        while ((len = is.read(bs)) != -1) {
                            os.write(bs, 0, len);
                        }
                        //将图片上传到服务器
                        URL xUrl = new URL("*************" + "/2/");
                        File excelFile = File.createTempFile(uuid32, last);
                        File file = new File(sf.getPath() + "/" + uuid32 + last);
                        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                        PutObjectResult putObjectResult = ossClient.putObject("starwant-dev", "2/" + uuid32 + last, file);
                        os.close();
                        is.close();
                        ossClient.shutdown();
                        this.deleteFile(excelFile);
                        this.deleteFile(file);
                        //替换图片url
                        String replaceHttp = xUrl + uuid32 + last;
                        String countx = count.replace(String.valueOf(url1), replaceHttp);
                        count = countx;
                    }
                }else {
                    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));
                        String last = getUrl(String.valueOf(url));
                        URLConnection con = url.openConnection();
                        con.setConnectTimeout(120 * 1000);
                        InputStream is = con.getInputStream();
                        byte[] bs = new byte[1024];
                        int len;
                        String xxUrl = "temp";
                        File sf = new File(xxUrl);
                        if (!sf.exists()) {
                            sf.mkdirs();
                        }
                        String uuid32 = getUUID32();
                        OutputStream os = new FileOutputStream(sf.getPath() + "/" + uuid32 + last);
                        // 开始读取
                        while ((len = is.read(bs)) != -1) {
                            os.write(bs, 0, len);
                        }
                        //将图片上传到服务器
                        URL xUrl = new URL("***************" + "/2/");
                        File excelFile = File.createTempFile(uuid32, last);
                        File file = new File(sf.getPath() + "/" + uuid32 + last);
                        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                        PutObjectResult putObjectResult = ossClient.putObject("starwant-dev", "2/" + uuid32 + last, file);
                        os.close();
                        is.close();
                        ossClient.shutdown();
                        this.deleteFile(excelFile);
                        this.deleteFile(file);
                        //替换图片url
                        String replaceHttp = xUrl + uuid32 + last;
                        String countx = count.replace(String.valueOf(url), replaceHttp);
                        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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值