記一次將圖片轉成base64上傳至服務器

1、首先先簡單看一下項目中的前端圖片部分代碼和js

圖片部分DIV

 <div class="head-infor head-top">
        <div class="infor-left">頭像</div>
        <div @click="handleHead()"  class="infor-right">
          <img id="img" class="infor-img" :src=headImg />
          <img class="infor-join" :src=join />
        </div >
      </div>

圖片上傳部分js

uploads(c, d) {
				var that = this
				"use strict";
				//獲取選擇圖片的個數
				var $c = document.querySelector(c),
					$d = document.querySelector(d),
					file = $c.files[0],
					reader = new FileReader();
				reader.readAsDataURL(file);
				reader.onload = function(e) {
					$d.setAttribute("src", e.target.result);
					console.log("*****################################***********")
					console.log(e.target)
					imgs=e.target.result;
					that.isFileCamra = false
				};
			},
    },

imgs是一個全局變量 我用來獲取圖片轉換成base64後的結果
imgs如下
在這裏插入圖片描述

2、ajax部分
需要注意 ajax要使用post的方式,而且向後臺傳送的數據要爲json格式的,我的代碼如下

$.ajax({ 
	type : "POST",  
	url : requertUrl + '/test',  
	contentType : "application/json ; charset=utf-8",
	dataType:"json", 
	data:JSON.stringify({
	"img":imgs,"userId":"123456"
	}),
	success : function(result) {
	},
	error:function(result) {
	},
})

3、後臺接收以JsonObject方式接收

    @RequestMapping("/test")
    public String fileupdate(HttpServletRequest request, @RequestBody JSONObject json) {
        try {
            System.out.println("*****************");
            Map<String,Object> map = new FileUploadUtils().jsonToMap(json);
            System.out.println(map.get("userId"));
          return "666";
        } catch (Exception e) {
            return "error";
        }

    }
}

圖片上傳的方法和JsonObject對象解析

將base64解析成圖片並保存至服務器

   /**
     * @Author shanzz
     * @Description //TODO 將base64轉換成圖片
     * @Date 18:53 2019/3/26
     * @Param [base64]
     * @return boolean
     **/

    public static String base64ToImage(String base64) {// 對字節數組字符串進行Base64解碼並生成圖片
        if (base64 == null){ // 圖像數據爲空
            return "null";
        }
        BASE64Decoder base64Decoder = new BASE64Decoder();
        createDir(ReadConfigUtils.getConfig("uploadFile"));
        String rootpath = ReadConfigUtils.getConfig("uploadFile")+"/";
        String fileType="jpg";
        String filename = "pic"+System.currentTimeMillis()+"."+fileType;
        String savepath= rootpath + filename;
        try {
//            byte[] bytes = base64Decoder.decodeBuffer(base64);
            if(base64.contains("data:image/png;base64,")){
                base64 = base64.replace("data:image/png;base64,","");
            }else if(base64.contains("data:image/jpg;base64,")){
                base64 = base64.replace("data:image/jpg;base64,","");
            }else if(base64.contains("data:image/jpeg;base64,")){
                base64 = base64.replace("data:image/jpeg;base64,","");
            }else if(base64.contains("data:image/gif;base64,")){
                base64 = base64.replace("data:image/gif;base64,","");
            }
            byte[] bytes = Base64.decodeBase64(base64);
//            base64 = base64.replace("base64,","");
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 調整異常數據
                    bytes[i] += 256;
                }
            }
            // 生成圖片
            OutputStream out = new FileOutputStream(savepath);
            out.write(bytes);
            out.flush();
            out.close();
            return filename;
        } catch (Exception e) {
            System.out.println("生成圖片失敗:PhotoUtils.changeBase64()");
            return "null";
        }
    }

解析JsonObject


 /**
     * @Author shanzz
     * @Description //TODO 解析參數
     * @Date 14:39 2019/3/27
     * @Param [jsonObject]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     *
     *       特別注意事項:
     *            如果涉及圖片上傳 前臺在傳參數時請統一將參數名設置爲img
    **/

    public Map<String,Object> jsonToMap(JSONObject jsonObject) {
        Map<String,Object> maps = new HashMap<>();
        Iterator<String> it = jsonObject.keys();
        while(it.hasNext()) {
            // 獲得key
            String key = it.next();
            String value = jsonObject.getString(key);
            if (key.equals("img")) {
                String imgName = base64ToImage(value);
                maps.put(key, imgName);
            }
            maps.put(key, value);
        }
        return maps;
        }

我這裏將我前臺傳的所有數據解析保存在了Map裏面,用於去保存數據庫中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章