注意: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;
}