Java Remote Download picture

Source: Internet
Author: User
Tags tag name stringbuffer

When copying an article from another website, download the image to our website and replace it with the address of our website.

  

<script type= "text/javascript" >window. Nextpic=function(url,name) {    var cb = "http://localhost:8080" +URL    Console.log ("haha");     var src = document.getElementById (name). src    ifreturn;     = CB;} </script>

 Public classWanewsinfovoextendsPage<wanewsinfo>{        PrivateInteger ID; PrivateString title; PrivateInteger typeId; PrivateString TypeName; PrivateInteger typeId2; PrivateString typeName2; PrivateString logo; PrivateString content; PrivateString Createtime; PrivateString CreateUser; PrivateString Createusername; PrivateString Tag1; PrivateString Tag2; PrivateInteger Isdisplay; PrivateInteger Browser; PrivateString Summary;}

Coding
private static final String ecoding = "UTF-8";
Get the IMG tag regular
private static final String Imgurl_reg = "]*?> ";
Gets the regular of the SRC path
private static final String Imgsrc_reg = "(Http|https): \"? (.*?) (\ "|>|\\s+)";


Add or modify information public int insertorupdate (httpservletrequest request, Wanewsinfovo vo) {String AAA = "/attached/image/"; String path = Request.getsession (). Getservletcontext (). Getrealpath (".. /") +"/attached/image/";//Get Picture label list<string> Imgurl = Getimageurl (Vo.getcontent ());//Get Picture src address list< string> imgsrc = getimagesrc (imgurl); Download Image Download (imgsrc,path); String test = Replacehtmltag (Vo.getcontent (), "img", "src", "src=\" "+aaa," \ ""); Vo.setcontent (test); if (Commutil.isempty (Vo.getid ())) {vo.setbrowser (0); return Wanewsdao.insert (VO);} Return Wanewsdao.update (VO);}

   /*** * Get imageurl address * *@paramHTML *@return      */      PrivateList<string>Getimageurl (String HTML) {Matcher Matcher=Pattern.compile (Imgurl_reg). Matcher (HTML); List<String> Listimgurl =NewArraylist<string>();  while(Matcher.find ()) {Listimgurl.add (Matcher.group ()); }          returnListimgurl; }     /*** * Get HTML content * *@paramURL *@return      * @throwsException*/      PrivateString gethtml (string url)throwsException {URL uri=Newurl (URL); URLConnection Connection=uri.openconnection (); InputStream in=Connection.getinputstream (); byte[] buf =New byte[1024]; intLength = 0; StringBuffer SB=NewStringBuffer ();  while(length = In.read (buf, 0, buf.length)) > 0) {sb.append (NewString (buf, ecoding));          } in.close (); returnsb.tostring (); }      /*** * Get IMAGESRC address * *@paramListimageurl *@return      */      PrivateList<string> Getimagesrc (list<string>Listimageurl) {List<String> LISTIMGSRC =NewArraylist<string>();  for(String image:listimageurl) {Matcher Matcher=Pattern.compile (Imgsrc_reg). Matcher (image);  while(Matcher.find ()) {Listimgsrc.add (Matcher.group (). Substring (0, Matcher.group (). Length ()-1)); }          }          returnlistimgsrc; }      /*** * Download Image * *@paramlistimgsrc*/      Private voidDownload (list<string>listimgsrc, String Path) {          Try {               for(String url:listimgsrc) {if(Url.indexof ("http") >=0) {String imageName= Url.substring (Url.lastindexof ("/") + 1, Url.length ()); URL URI=Newurl (URL); InputStream in=Uri.openstream (); FileOutputStream fo=NewFileOutputStream (NewFile (path,imagename)); byte[] buf =New byte[1024]; intLength = 0; System.out.println ("Start Download:" +URL);  while(length = In.read (buf, 0, buf.length))! =-1) {fo.write (buf,0, length);                  } in.close ();                  Fo.close (); System.out.println (Path+imagename + "Download Complete"); }            }          } Catch(Exception e) {System.out.println ("Download Failed"); }      }     

Replace IMG Tag

    /*** Replace the properties and values of the specified label *@paramstring to be processed by STR *@paramtag Tag name *@paramTagattrib the Tag property value to replace *@paramstarttag new Tag start tag *@paramEndtag new Tag end tag *@return      * @authorHuweijun * @date July 13, 2016 PM 7:15:32*/       Public Staticstring Replacehtmltag (String str, string tag, string tagattrib, String Starttag, String endtag) {//match with  EndString Regxpfortag = "<\\s*" + Tag + "\\s+ ([^>]*) \\s*" ; //match src= "Start," EndString Regxpfortagattrib = tagattrib + "=\\s*\" ([^\ "]+) \" " ; //Post-compiled regular expressionsPattern Patternfortag =Pattern.compile (Regxpfortag,pattern.          case_insensitive); Pattern Patternforattrib=Pattern.compile (Regxpfortagattrib,pattern.        case_insensitive); //Check the Matcher Matcherfortag =Patternfortag.matcher (str); StringBuffer SB=NewStringBuffer (); //If there is a result        Booleanresult =Matcherfortag.find ();  while(Result) {StringBuffer sbreplace=NewStringBuffer ("<" +tag+ ""); //find the first Matcher Matcherforattrib = Patternforattrib.matcher (Matcherfortag.group (1)); if(Matcherforattrib.find ()) {String attributestr= Matcherforattrib.group (1); String ImageName= Attributestr.substring (Attributestr.lastindexof ("/") + 1, Attributestr.length ()); Sbreplace.append ("Id=" "+imagename+" ' alt= ' picture ' onerror=\ ' nextpic ('/attached/image/' +imagename+ "', '" +imagename+ "'); \" "); Matcherforattrib.appendreplacement (Sbreplace, Starttag+ "Rcwimg" +Endtag);              } matcherforattrib.appendtail (Sbreplace);              Matcherfortag.appendreplacement (SB, sbreplace.tostring ()); Result=Matcherfortag.find ();                   } matcherfortag.appendtail (SB); returnsb.tostring (); }      

Java Remote Download picture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.