1. Save to server
Save the path to the server on which the project resides.
1String imgurl= "";//Image Address2 Try {3 //construct URL4URL url =NewURL (imgurl);5 //Open Connection6URLConnection con =url.openconnection ();7 //input Stream8InputStream is =Con.getinputstream ();9 //1K of data bufferingTen byte[] bs =New byte[1024]; One //length of data read A intLen; - //the output file stream -OutputStream OS =NewFileOutputStream ("c:\\image.jpg");//Save Path the //start reading - while(len = Is.read (BS))! =-1) { -Os.write (BS, 0, Len); - } + //complete, close all links - os.close (); + is.close (); A}Catch(malformedurlexception e) { at e.printstacktrace (); -}Catch(FileNotFoundException e) { - e.printstacktrace (); -}Catch(IOException e) { - e.printstacktrace (); -}
2. Save to Local
Saved locally as a browser download.
1String imgurl= "";//URL address2String fileName = imgurl.substring (Imgurl.lastindexof ('/') + 1);3Bufferedinputstream is =NULL;4Bufferedoutputstream OS =NULL;5 Try {6URL url =NewURL (imgurl);7 This. Getservletresponse (). setContentType ("application/x-msdownload;"); 8 This. Getservletresponse (). SetHeader ("Content-disposition", "attachment; Filename= "+NewString (Filename.getbytes ("Utf-8"), "Iso8859-1")); 9 This. Getservletresponse (). SetHeader ("Content-length", String.valueof (Url.openconnection (). Getcontentlength ())); Tenis =NewBufferedinputstream (Url.openstream ()); OneOS =NewBufferedoutputstream ( This. Getservletresponse (). Getoutputstream ()); A byte[] Buff =New byte[2048]; - intBytesread; - while( -1! = (bytesread = is.read (buff, 0, Buff.length))) { theOs.write (Buff, 0, Bytesread); - } - if(Is! =NULL) - Is.close (); + if(OS! =NULL) - os.close (); +}Catch(malformedurlexception e) { A e.printstacktrace (); at}Catch(unsupportedencodingexception e) { - e.printstacktrace (); -}Catch(IOException e) { - e.printstacktrace (); -}
Download pictures to client, server instance according to URL