ajax圖片上傳(BASE64)(文件服務)

注意:img標籤src加載不了https開頭的圖片地址,用base64碼

1、前端

<form id="pointPhotoForm" class="form-horizontal" name="pointPhotoForm" enctype="multipart/form-data">
	<div class="col-md-4">
		<input type="file" id="pic1" name="pic1" style="width: 100%;" onchange='uploadFile("tp1")'>
	</div>
	<div class="col-md-4">
		<input type="file" id="pic2" name="pic2" style="width: 100%;" onchange='uploadFile("tp2")'>
	</div>
	<div class="col-md-4">
		<input type="file" id="pic3" name="pic3" style="width: 100%;" onchange='uploadFile("tp3")'>
	</div>
</form>


<script>
function uploadFile(myfile) {
	showMask();
	var id = document.getElementById("id").value;
	var state = document.getElementById("state").value;
	var tp1 = document.getElementById("pic1").files[0];
	var tp2 = document.getElementById("pic2").files[0];
	var tp3 = document.getElementById("pic3").files[0];
	var fm = new FormData();
	fm.append('id', id);
	fm.append('state', state);
	fm.append('tp1', tp1);
	fm.append('tp2', tp2);
	fm.append('tp3', tp3);
	fm.append('myfile', myfile);
	$.ajax({
		url: '/updatePointPhoto',
		type: 'POST',
		data: fm,
		dataType: 'json',
		contentType: false, //禁止設置請求類型 
		processData: false, //禁止jquery對DAta數據的處理,默認會處理 //禁止的原因是,FormData已經幫我們做了處理
		/* beforeSend: LoadFunction, //加載執行方法 */
		success: function (json) {
			//測試是否成功 //但需要你後端有返回值 
			hideMask();
			debugger;
			var mydata = json.data;
			document.getElementById(myfile).setAttribute("src",mydata);
			document.getElementsByName(myfile)[0].value = json.imgurl;
		}
	});
}
</script>

2、後端

	@RequestMapping(value = "/updatePointPhoto", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@RequiresPermissions(value = PermissionSign.DWXXCX)
	@SystemControllerLog(description="上傳圖片信息", className="DwController", methodName="updatePointPhoto")
	@ResponseBody
	public String UpdatePoint(String id,String state, MultipartFile tp1,MultipartFile tp2,MultipartFile tp3, String myfile) {
		Map<String, Object> map = Maps.newHashMap();
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			if ("tp1".equals(myfile)) {
				if (!"".equals(tp1) && tp1 != null) {
					String pic1 = encoder.encode(tp1.getBytes());
					pic1 = pic1.replaceAll("[\\s*\t\n\r]", "");
					if (saveHTTPSServerPic("1", "20181130", id, pic1)) {
						String imgurl = String.format("%s?jlbh=%s&testdate=%s&filename=1.jpg", GlobalSettings.getConfig("getSpicURL"),id,"20181130");
						map.put("data", "data:image/png;base64,"+pic1);
						map.put("imgurl", imgurl);
					}
				}
			}else if ("tp2".equals(myfile)) {
				if (!"".equals(tp2) && tp2 != null) {
					String pic2 = encoder.encode(tp2.getBytes());
					pic2 = pic2.replaceAll("[\\s*\t\n\r]", "");
					if (saveHTTPSServerPic("2", "20181130", id, pic2)) {
						String imgurl = String.format("%s?jlbh=%s&testdate=%s&filename=2.jpg", GlobalSettings.getConfig("getSpicURL"),id,"20181130");
						map.put("data", "data:image/png;base64,"+pic2);
						map.put("imgurl", imgurl);
					}
				}
			}else {
				if (!"".equals(tp3) && tp3 != null) {
					String pic3 = encoder.encode(tp3.getBytes());
					pic3 = pic3.replaceAll("[\\s*\t\n\r]", "");
					if (saveHTTPSServerPic("3", "20181130", id, pic3)) {
						String imgurl = String.format("%s?jlbh=%s&testdate=%s&filename=3.jpg", GlobalSettings.getConfig("getSpicURL"),id,"20181130");
						map.put("data", "data:image/png;base64,"+pic3);
						map.put("imgurl", imgurl);
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			map.put("code", "0");
			map.put("message","提交文件異常");
			e.printStackTrace();
		}
		
		String ret = JSONUtil.map2json(map);
		return ret;
	}
//http(POST)

private boolean saveServerPic(String type, String date, String jlbh, String base64pic){
		PrintWriter out = null;
        BufferedReader in = null;
        boolean res = false;
        String result = "";
		if (base64pic == null || base64pic.length() == 0)
		    return res;
        try {
            URL realUrl = new URL(GlobalSettings.getConfig("postSpicURL"));
            String param = "base64=" + base64pic + "&jlbh=" + jlbh + "&testdate=" + date + "&filename=" + type +".jpg";
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發送POST請求必須設置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 發送請求參數
            out.print(param);
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject json = JSONObject.fromObject(result);
            res = "0".equals(json.getString("errno"));
        } catch (Exception e) {
            System.out.println("發送 POST 請求出現異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return res;
	}
//https(POST)

/*
 * @param url   需要請求的網關路徑
 * @param sendData  請求時需要傳入的參數
 * @param urlencode url的編碼格式
 * @param connTimeOut   鏈接超時時間 
 * @param readTimeOut   讀取超時時間
 * @param contentType   請求頭部  固定輸入"application/x-www-form-urlencoded;charset="+urlencode
 * @param header     輸入null
 * @return
 */
private boolean saveHTTPSServerPic(String type, String date, String jlbh, String base64pic){
	boolean res = false;
    String result = "";
    BufferedReader in = null;
    DataOutputStream out = null;
    int code = 999;
    HttpsURLConnection httpsConn = null;
    HttpURLConnection httpConn = null;

    //HTTPS POST默認數據項
    String urlencode = "UTF-8";
    int connTimeOut = 60000;
    int readTimeOut = 60000;
    String contentType = "application/x-www-form-urlencoded;charset=UTF-8";
    Map<String,String> header = null;
    
	if (base64pic == null || base64pic.length() == 0){
		return res;
	}
	try{
		String url = GlobalSettings.getConfig("postSpicURL");
		String sendData = "base64=" + base64pic + "&jlbh=" + jlbh + "&testdate=" + date + "&filename=" + type +".jpg";
        URL myURL = new URL(url);
        if(url.startsWith("https://")){
            httpsConn =    (HttpsURLConnection) myURL.openConnection();
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                        }
                        public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                        }
                    }
                };
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConn.setSSLSocketFactory(sc.getSocketFactory());
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            }; 
            httpsConn.setHostnameVerifier(hv);
            
            httpsConn.setRequestProperty("Accept-Charset", urlencode);
            httpsConn.setRequestProperty("User-Agent","java HttpsURLConnection");
            if(header!=null){
                for(String key:header.keySet()){
                    httpsConn.setRequestProperty(key, (String)header.get(key));
                }
            }
            httpsConn.setRequestMethod("POST");
            httpsConn.setUseCaches(false);
            httpsConn.setRequestProperty("Content-Type",contentType);
            httpsConn.setConnectTimeout(connTimeOut);
            httpsConn.setReadTimeout(readTimeOut);
            httpsConn.setDoInput(true);
            httpsConn.setInstanceFollowRedirects(true); 
            if(sendData !=null){
                httpsConn.setDoOutput(true);
                // 獲取URLConnection對象對應的輸出流
                out = new DataOutputStream(httpsConn.getOutputStream());
                // 發送請求參數
                out.write(sendData.getBytes(urlencode));
                // flush輸出流的緩衝
                out.flush();
                out.close();
            }
            // 取得該連接的輸入流,以讀取響應內容
            in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(),urlencode));
            code = httpsConn.getResponseCode();
        }else{
            httpConn =    (HttpURLConnection) myURL.openConnection();
            httpConn.setRequestProperty("Accept-Charset", urlencode);
            httpConn.setRequestProperty("user-agent","java HttpURLConnection");
            if(header!=null){
                for(String key:header.keySet()){
                    httpConn.setRequestProperty(key, (String)header.get(key));
                }
            }
            httpConn.setRequestMethod("POST");
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Content-Type",contentType); 
            httpConn.setConnectTimeout(connTimeOut);
            httpConn.setReadTimeout(readTimeOut);
            httpConn.setDoInput(true);
            httpConn.setInstanceFollowRedirects(true); 
            if(sendData !=null){
                httpConn.setDoOutput(true);
                // 獲取URLConnection對象對應的輸出流
                out = new DataOutputStream(httpConn.getOutputStream());
                // 發送請求參數
                out.write(sendData.getBytes(urlencode));
                // flush輸出流的緩衝
                out.flush();
                out.close();
            }
            // 取得該連接的輸入流,以讀取響應內容
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),urlencode));
            code = httpConn.getResponseCode();
        }
        if (HttpURLConnection.HTTP_OK == code){ 
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject json = JSONObject.fromObject(result);
            res = "0".equals(json.getString("errno"));
        }else{
            result = null;
        }
    }catch(IOException e){
    	System.out.println("http通訊失敗:" + e.getMessage());
        result = null;
    }catch(Exception e){
    	System.out.println("http通訊失敗:" + e.getMessage());
        result = null;
    }finally{
        //Trace.logInfo(Trace.COMPONENT_ACTION,"對方地址:"+url);
        if(out!=null){
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if(httpConn!=null){
            httpConn.disconnect();
        }
        if(httpsConn!=null){
            httpsConn.disconnect();
        }
        if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
	return res;
}
//http(GET)

public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
        	param = URLEncoder.encode(param, "UTF-8");
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設置通用的請求屬性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連接
            connection.connect();
            // 獲取所有響應頭字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍歷所有的響應頭字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發送GET請求出現異常!" + e);
            e.printStackTrace();
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    //https(GET)
    public static String sendAndRcvHttpGetBase(String url,String sendData,String urlencode,int connTimeOut,int readTimeOut,String contentType,Map<String,String> header){
        String result = "";
        BufferedReader in = null;
        DataOutputStream out = null;
        int code = 999;
        HttpsURLConnection httpsConn = null;
        HttpURLConnection httpConn = null;
        try{
        	if(null == sendData || "".equals(sendData)){
            }else{
            	url = url + "?" + URLEncoder.encode(sendData, urlencode);
            }
            URL myURL = new URL(url);
            if(url.startsWith("https://")){
                httpsConn =    (HttpsURLConnection) myURL.openConnection();
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return null;
                            }
                            public void checkClientTrusted(
                                java.security.cert.X509Certificate[] certs, String authType) {
                            }
                            public void checkServerTrusted(
                                java.security.cert.X509Certificate[] certs, String authType) {
                            }
                        }
                    };
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                httpsConn.setSSLSocketFactory(sc.getSocketFactory());
                HostnameVerifier hv = new HostnameVerifier() {
                    @Override
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                }; 
                httpsConn.setHostnameVerifier(hv);
                    
                httpsConn.setRequestProperty("Accept-Charset", urlencode);
                httpsConn.setRequestProperty("User-Agent","java HttpsURLConnection");
                if(header!=null){
                    for(String key:header.keySet()){
                        httpsConn.setRequestProperty(key, (String)header.get(key));
                    }
                }
                httpsConn.setRequestMethod("GET");
                httpsConn.setUseCaches(false);
                httpsConn.setRequestProperty("Content-Type",contentType); 
                httpsConn.setConnectTimeout(connTimeOut);
                httpsConn.setReadTimeout(readTimeOut);
                httpsConn.setDoInput(true);
                httpsConn.setInstanceFollowRedirects(true);
                httpsConn.connect();
                // 取得該連接的輸入流,以讀取響應內容
                in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(),urlencode));
                code = httpsConn.getResponseCode();
            }else{
                httpConn =    (HttpURLConnection) myURL.openConnection();
                httpConn.setRequestProperty("Accept-Charset", urlencode);
                httpConn.setRequestProperty("user-agent","java HttpURLConnection");
                if(header!=null){
                    for(String key:header.keySet()){
                        httpConn.setRequestProperty(key, (String)header.get(key));
                    }
                }
                httpConn.setRequestMethod("GET");
                httpConn.setUseCaches(false);
                httpConn.setRequestProperty("Content-Type",contentType); 
                httpConn.setConnectTimeout(connTimeOut);
                httpConn.setReadTimeout(readTimeOut);
                httpConn.setDoInput(true);
                httpConn.setInstanceFollowRedirects(true); 
                httpConn.connect();
                // 取得該連接的輸入流,以讀取響應內容
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),urlencode));
                code = httpConn.getResponseCode();
            }
            if (HttpURLConnection.HTTP_OK == code){ 
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }else{
                result = null;
            }
        }catch(IOException e){
        	System.out.println("http通訊失敗:" + e.getMessage());
            result = null;
        }catch(Exception e){
        	System.out.println("http通訊失敗:" + e.getMessage());
            result = null;
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if(httpConn!=null){
                httpConn.disconnect();
            }
            if(httpsConn!=null){
                httpsConn.disconnect();
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }
@RequestMapping(value = "/pointPhotoInfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	@RequiresPermissions(value = PermissionSign.DWXXCX)
	@SystemControllerLog(description="獲取圖片信息", className="DwController", methodName="getPointPhotoInfo")
	public String getPointPhotoInfo(String id, Model model) {
		MonitoringPoint point = dwxxService.getPointPhotoInfo(id);
		if (point.getTp1() != null && !"".equals(point.getTp1()) && !"undefined".equals(point.getTp1())) {
			point.setTp1("data:image/png;base64,"+new String(HttpsUtil.sendAndRcvHttpGetBase(point.getTp1()+"&isbase64=1", null, "utf-8", 60000, 60000, "application/x-www-form-urlencoded;charset=utf-8", null)));
		}
		if (point.getTp2() != null && !"".equals(point.getTp2()) && !"undefined".equals(point.getTp2())) {
			point.setTp2("data:image/png;base64,"+new String(HttpsUtil.sendAndRcvHttpGetBase(point.getTp2()+"&isbase64=1", null, "utf-8", 60000, 60000, "application/x-www-form-urlencoded;charset=utf-8", null)));
		}
		if (point.getTp3() != null && !"".equals(point.getTp3()) && !"undefined".equals(point.getTp3())) {
			point.setTp3("data:image/png;base64,"+new String(HttpsUtil.sendAndRcvHttpGetBase(point.getTp3()+"&isbase64=1", null, "utf-8", 60000, 60000, "application/x-www-form-urlencoded;charset=utf-8", null)));
		}
		model.addAttribute("pointinfodetail", point);
		return "monitoringpointinfo/pointphotoinfo";
	}

注:不要在服務器端一次獲取多張圖片,會致使服務器端壓力較大,前端加載圖片,Modal頁面過慢(出現重現其他Modal頁面問題),可以利用jQuery前端訪問後端一張一張加載,先加載頁面,後加載圖片。

<!-- 前端 -->
<img id="pic-img1" >
<img id="pic-img2" >

<script>
jQuery(document).ready(function() {
	getimg();
});

function getimg(){
	var tp1 = "${nitoringinfodetail.tp1 }";
	var tp2 = "${nitoringinfodetail.tp2 }";
	var pdjg = '${nitoringinfodetail.pdjg }';
	var url1 = tp1+"&isbase64=1";
	var url2 = tp2+"&isbase64=1";
	if(pdjg=='通過'||pdjg=='不判定'){

	}else{
		var params = {};
		params.tp1 = url1;
		var url = "/getimg";
		$.post(url,params, function(data) {
			if(data==null||data==""){
				return;
			}else{
					var imgsrc = "data:image/png;base64,"+data;
					document.getElementById("pic-img1").src=imgsrc;
					document.getElementById("pic-img1").height="150";
			}
			
		});
		var params2 = {};
		params2.tp1 = url2;
		$.post(url,params2, function(data) {
			if(data==null||data==""){
				return;
			}else{
					var imgsrc = "data:image/png;base64,"+data;
					document.getElementById("pic-img2").src=imgsrc;
					document.getElementById("pic-img2").height="150";
				
			}
			
		});
	}
};
  
</script>
//後端

@RequestMapping(value = "/getimg", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@SystemControllerLog(description="獲取圖片", className="CentermapController", methodName="getimg")
	@ResponseBody
	@RequiresPermissions(value = PermissionSign.JGDT)
	public String getimg(MonitoringPoint mp,Model model) {
		String imgurl = mp.getTp1();
		AuditInfo auditInfo = new AuditInfo();
		String output = "";
		try {
			auditInfo.setFuncid(PermissionSign.JGDT);
			auditInfo.setOperation("查詢");
			auditInfo.setPagename("/getimg");
			auditInfo.setDescription("");
			auditInfo.setTimestamp(new Date(System.currentTimeMillis()));
			auditInfo.setUserid(PublicUtil.getLoginUser().getUserid());
			try {
				auditInfo.setIp(NetworkUtil.getIpAddress(request));
			} catch (IOException e) {
				e.printStackTrace();
				auditInfo.setIp("127.0.0.1");
			}
			//List<Map<String, Object>> list = null;
			String urlString = imgurl;
	        output = new String(HttpsUtil.sendAndRcvHttpGetBase(imgurl, null, "utf-8", 60000, 60000, "application/x-www-form-urlencoded;charset=utf-8", null));
			super.szCode = GlobalSettings.SysReturnCode.Success.getKey() + "";
			auditInfo.setResult("成功");
		} catch(LogicException ex){
			ex.printStackTrace();
			auditInfo.setResult("失敗");
			super.szCode = GlobalSettings.SysReturnCode.Failure.getKey() + "";
			super.szMessage = ex.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			auditInfo.setResult("失敗");
			super.szCode = GlobalSettings.SysReturnCode.Failure.getKey() + "";
			super.szMessage = e.getMessage();
		}
		auditService.insertAuditInfo(auditInfo);
		
		return output;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章