1. 程式人生 > >在後臺轉換base64格式的圖片,讓資料庫存貯伺服器端圖片。

在後臺轉換base64格式的圖片,讓資料庫存貯伺服器端圖片。

public String parseContents(String contents) {

        String newContents=new String();
        while (contents.indexOf("data:image/") != -1) {

            int firstIndex = contents.indexOf("data:image/") + 11;
            int index1 = contents.indexOf(";base64,");
           // int index2 = contents.indexOf("\"", index1);

            String type = contents.substring(firstIndex, index1);
            // img.do
            String fileName = "E:/uploadFiles/" + UUID.randomUUID().toString() + "." + type;
            //開始轉碼,然後將當前檔案寫入圖片資料。
            System.out.println(fileName);
            BASE64Decoder decoder = new BASE64Decoder();
            OutputStream os = null;
            try {
                String imgsrc= StringUtils.substringBefore(contents.substring(contents.indexOf(";base64,") + 8),"\"");
                System.out.println(imgsrc);

                byte[] bytes = decoder.decodeBuffer(imgsrc);
                newContents=contents.replace("data:image/"+type+";base64,"+imgsrc,"/images.do?src="+fileName);
                System.out.println(newContents+">>>\n"+contents);
                File file = new File(fileName);
                //獲取父目錄
                File fileParent = file.getParentFile();
                //判斷是否存在
                if (!fileParent.exists()) {
                    //建立父目錄檔案
                    fileParent.mkdirs();
                }
                file.createNewFile();
                os = new FileOutputStream(file);
                os.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        return newContents;
    }