|
@@ -0,0 +1,86 @@
|
|
|
+package com.caimei.www.utils;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.jsoup.Jsoup;
|
|
|
+import org.jsoup.nodes.Element;
|
|
|
+import org.jsoup.select.Elements;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.io.FileOutputStream;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.io.OutputStream;
|
|
|
+import java.net.URL;
|
|
|
+import java.net.URLConnection;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Description
|
|
|
+ *
|
|
|
+ * @author : Charles
|
|
|
+ * @date : 2021/5/28
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+public class GetProductImgUtil {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 保存图片到本地服务器
|
|
|
+ * @param textBody 富文本
|
|
|
+ */
|
|
|
+ public static void saveProductImg(String textBody) {
|
|
|
+ // 解析富文本
|
|
|
+ Element doc = Jsoup.parseBodyFragment(textBody).body();
|
|
|
+ Elements images = doc.select("img[src]");
|
|
|
+ List<String> srcList = new ArrayList<>();
|
|
|
+ for (Element element : images) {
|
|
|
+ String imgUrl = element.attr("src");
|
|
|
+ // 筛选测试服务器的图片路径
|
|
|
+ if (imgUrl.indexOf("img-b.caimei365.com") > 0) {
|
|
|
+ srcList.add(imgUrl);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 本地存放路径
|
|
|
+ String basePath = "D:/mnt/newdatadrive/fdfs/storage/data/";
|
|
|
+ srcList.forEach(img -> {
|
|
|
+ try {
|
|
|
+ // 下载图片,并根据路径规律保持原有路径
|
|
|
+ GetProductImgUtil.downloadImage(img, img.substring(45), basePath+img.substring(39, 45));
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("try-catch:",e);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 下载图片
|
|
|
+ *
|
|
|
+ * @param urlString 图片链接
|
|
|
+ * @param filename 图片名称
|
|
|
+ * @param savePath 保存路径
|
|
|
+ */
|
|
|
+ private static void downloadImage(String urlString, String filename, String savePath) throws Exception {
|
|
|
+ // 构造URL打开连接,并设置输入流与缓冲
|
|
|
+ URL url = new URL(urlString);
|
|
|
+ URLConnection con = url.openConnection();
|
|
|
+ con.setConnectTimeout(5*1000);
|
|
|
+ InputStream is = con.getInputStream();
|
|
|
+ byte[] bs = new byte[1024];
|
|
|
+ // 读取到的数据长度
|
|
|
+ int len;
|
|
|
+ // 输出的文件流
|
|
|
+ File sf=new File(savePath);
|
|
|
+ if(!sf.exists()){
|
|
|
+ sf.mkdirs();
|
|
|
+ }
|
|
|
+ OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
|
|
|
+ // 开始读取
|
|
|
+ while ((len = is.read(bs)) != -1) {
|
|
|
+ os.write(bs, 0, len);
|
|
|
+ }
|
|
|
+ os.close();
|
|
|
+ is.close();
|
|
|
+ // 打印图片链接
|
|
|
+ log.info(urlString);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|