import com.yingping.site.FileNameHandle
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager
import org.apache.commons.httpclient.methods.GetMethod
Created by IntelliJ IDEA.
/*util class*/
class ImgDownload {
@param content 内容
@param savedPath 保存绝对路径
@param abPath 显示用路径 如:imagesdownloadImga.gif
@return
static String downLoadImg(String content, String savedPath, String abPath){
String html = content.toLowerCase() //第一步:将copy的网络内容转为小写
def list=new LinkedListString()
def matcher=html=~src=[' ]([^' ]) //第二步:通过正则表达式截取图片路径,得到img src的路径
if (matcher.hasGroup()) {
matcher.each{
list << it[1]
}
}
list.each{url->
if(url.startsWith('http')){
String newUrl =downloadBinaryFile(url,savedPath)
if(newUrl){
newUrl = currProjectName+abPath++newUrl 在数据库里保存为下面形式[cpath]imagesdownloadimga.jpg
content = content.replaceAll((i)+url+,newUrl) 加(i)是不区分大小写替换
}
}
}
return content
}
static String downloadBinaryFile(String address,String savePath) {
def input
def output
try {
System.getProperties().setProperty(httpclient.useragent, Mozilla4.0);
HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager())
GetMethod get = new GetMethod(address)
get.setRequestHeader(User-Agent,
Mozilla5.0 (Windows; U; Windows NT 5.1; zh-CN; rv1.9.2.13) Gecko20101203 Firefox3.6.13));
get.setFollowRedirects(true)
client.executeMethod(get)
String contentType = get.getResponseHeader(Content-Type).getValue()
contentType = contentType.toLowerCase()
String fileName = FileNameHandle.createName()//这个是调用了本人封装的一个获取唯一文件名的方法
String fileExt = contentType-'image'
if(['png','jpg','jpeg','gif'].grep(fileExt)){
String path =savePath + + fileName+.+fileExt
File file = new File(path)
input = get.getResponseBodyAsStream()
output = new BufferedOutputStream(new FileOutputStream(file))
output input
return fileName+.+fileExt
}else if(FileNameHandle.getExt(address)){
fileExt =FileNameHandle.getExt(address)()//这个是调用了本人封装的一个获取文件后缀的方法
String path =savePath + + fileName+.+fileExt
File file = new File(path)
input = get.getResponseBodyAsStream()
output = new BufferedOutputStream(new FileOutputStream(file))
return fileName+.+fileExt
}
}catch(Exception e){
e.printStackTrace()
} finally {
input.close()
output.close()
}
return null
}
/*Test main*/
public static void main(String[] args) {
String webUrl= '''
img src=httpimg01.taobaocdn.comtpsi1T1LJ4YXbhxXXXXXXXX-110-135.png
img border=0 height=29 src=httpimg20.360buyimg.comImgUploadvclistimg20109279305055402.jpg width=32 3.0英寸全触屏div '''
String savedPath = D
String newContent = ImgDownload.downLoadImg(webUrl,savedPath)
System.out.println(newContent)
}
}