对富文本内的图片链接替换

需求是这样的,由于我们的电商商品详情图的数据是老平台迁移过来的,商品详情图片是老平台的file数据仓库地址

需要迁移到 新平台oss;

不多说,上代码👇👇👇👇👇👇👇

 

package com.oak.controller.test;

import com.oak.dao.mapper.GoodsSPUMapper;
import com.oak.service.consume.UploadFeignClient;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.oak.common.constant.AppConstants.API_PATH;

/**
 * @author caozengling
 * @Description:
 * @date 2019/7/18
 */
@RestController
@RequestMapping(API_PATH)
@Validated
@Slf4j
public class DemoController {
    @Autowired
    private GoodsSPUMapper goodsSPUMapper;

    @Autowired
    private UploadFeignClient uploadFeignClient;

    /**
     *
     */
    @GetMapping("/test")
    @ApiOperation("")
    public Object queryCategoryByid() {
        String test = "<p><img src=\"https://img.alicdn.com/imgextra/i1/2891391837/O1CN011PRO2FsFf6k7539_!!2891391837.jpg\"></p>";
        String[] split = test.split("\"");
        List<String> res = new ArrayList<>();
        int start = 1;//开始
        for (int i = 0; i < split.length; i++) {
            if (0 == i % 2) {
                res.add(split[i]);
            } else {
                try {
                    downLoadFromUrl(split[i].toString(), "1.jpg", "d:/");
                    File newFile = new File("d:/1.jpg");
                    FileInputStream inputStream = new FileInputStream(newFile);
                    MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "image/jpeg", inputStream);
                    Map map = uploadFeignClient.uploadGoodsByimage(multipartFile, "goods-service", "1");
                    if (("0").equals(map.get("errorCode").toString())) {
                        List<HashMap<String, Object>> filelist = (List<HashMap<String, Object>>) map.get("data");
                        log.debug("上传返回参数->{}", filelist);
                        Object url = filelist.get(0).get("url");
                        System.out.println("成功------------------------》" + start++);
                        res.add(url.toString());
                    }
//                    res.add(split[i]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(res.toString().replace("[", "").replace("]", "").replace(",", "\""));
        return "success";
    }

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("info:" + url + " download success");
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) {
        try {
            downLoadFromUrl("http://imgservice3.suning.cn/uimg1/b2c/image/EJq-C3a0celo3Iri9MKsIA==.jpg_800w_800h_4e",
                    "1.jpg", "d:/");
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}

 

posted @ 2019-07-19 20:29  caozengling  阅读(2188)  评论(0编辑  收藏  举报