zoukankan      html  css  js  c++  java
  • JAVA获取一个图片路径后,下载该图片再重新上传至指定路径中

    需求如题。

    代码如下

      //filePath格式为““src='文件路径'””
      public void Test(String filePath){


         String filePath = GetHtmlImageSrcList(custom.getDescription()).get(0);//将文件路径通过正则表达式转换为http://XXX/XX的形式

        URL url = new URL(filePath);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
         connection.setConnectTimeout(30000);
         connection.setReadTimeout(30000);
         connection.connect();
    
         String fileName = filePath.substring(filePath.lastIndexOf("."));
         String photoUrl =
           OSSClientUtil.uploadFile2OSS(connection.getInputStream(),
               "scene/" + dateTimeSSSFormat.format(new Date()) + fileName);//框架已存在的文件上传方法,在此不赘述
      }
    
        /**
         * 获取IMG标签的SRC地址
         */
        public static List<String> GetHtmlImageSrcList(String htmlText) {
            List<String> imgSrc = new ArrayList<String>();
            Matcher m = Pattern.compile("src="?(.*?)("|>|\s+)").matcher(htmlText);
            while (m.find()) {
                imgSrc.add(m.group(1));
            }
    
            return imgSrc;
        }

    1、其中

    //URL aURL = new URL(“http://www.mycompany.com:8080/index.html”);

    我们创建了一个使用完整URL的URL class,其中明确指出了使用的协议是http,主机名称是www.mycompany.com,端口号码为8080,文件/资源为 index.html。如果组成URL的语法发生了错误,那么构造器就会发出MalformedURLException。

    openConnection并不需要参数,并且在操作成功之后,它会返回一个URLConnection class的实例。
    后续还有对URL内容的读写操作,可参考https://www.cnblogs.com/blackiesong/p/6182038.html中的解释。


    2、GetHtmlImageSrcList方法中用到了Pattern和Matcher两个类,这两个都在java提供的java.util.regex类工具包中。
    详细内容参考http://www.cnblogs.com/ggjucheng/p/3423731.html中的解释。



    3、正则表达式:可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
    语法参考http://www.runoob.com/regexp/regexp-syntax.html。
    https://baijiahao.baidu.com/s?id=1588848792548192879&wfr=spider&for=pc


  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/sjbas/p/10270698.html
Copyright © 2011-2022 走看看