1. 程式人生 > >neditor+秀米上傳圖片處理

neditor+秀米上傳圖片處理

上篇所說Neditor整合秀米操作,結尾丟擲一個問題,那就是圖片是秀米伺服器訪問的地址,而且沒有辦法再引入時訪問自己專案的服務儲存圖片,那麼應該從儲存上開始處理,獲取content內容,迴圈內容中的所有圖片伺服器,本人用的是正則匹配的方式:

/**
     * 根據content內容 獲取裡面img標籤的src屬性的值的列表
     * 
     * @param content
     * @return
     */
    public static List<String> getImgSrc(String content) {
        List<String> srcList = new ArrayList<String>(); 
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img[^>]*>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(content);
        while (m_image.find()) {
            // 得到<img />資料
            img = m_image.group();
            // 匹配<img>中的src資料
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            List<String> imgList = new ArrayList<String>();
            while (m.find()) {
                imgList.add(m.group(1));
            }
            //包含秀米伺服器的圖片放入srcList做處理
            if(imgList.get(0).contains("statics.xiumi.us")){
                srcList.add(imgList.get(0));
            }
        }
        return srcList;
    }

這樣就會匹配出所有的img標籤的所有src的值,因為秀米的圖片名稱也是唯一標識,所以不用擔心衝突問題,只要上傳伺服器後再替換掉原來的src值就可以了。

網路圖片下載到本地:

int beginPos = imgsrc.lastIndexOf(".");
//秀米圖片有可能後面還有特殊字元(?x-oss-process=style/xmorient)需要另作處理
int endPost = imgsrc.lastIndexOf("?");
if(endPost == -1){
    endPost = imgsrc.length();
}
String file_type = imgsrc.substring(beginPos+1, endPost);
file_type = file_type.equals("") ? "png" : file_type;
String file_name = UUID.randomUUID().toString().replaceAll("-", "") + "." + file_type;

URL url = new URL(imgsrc);/* 將網路資源地址傳給,即賦值給url */
/* 此為聯絡獲得網路資源的固定格式用法,以便後面的in變數獲得url擷取網路資源的輸入流 */
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
/* 此處也可用BufferedInputStream與BufferedOutputStream */
DataOutputStream out = new DataOutputStream(new FileOutputStream("tmp/uploads/"+file_name));//磁碟目錄
/* 將引數savePath,即將擷取的圖片的儲存在本地地址賦值給out輸出流所指定的地址 */
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0)/* 將輸入流以位元組的形式讀取並寫入buffer中 */
{
    out.write(buffer, 0, count);
}
out.close();/* 後面三行為關閉輸入輸出流以及網路資源的固定格式 */
in.close();
connection.disconnect();

下載本地需要上傳,具體結合自己的專案的邏輯來寫就可以了。