如果js不能跨域访问本地资源,比如说图片,可以考虑通过请求的方式,通过后台访问返回到前台显示,示例如下:
后台:
/** * 后台读取卫星图片返回到前台显示 * @param imgName * @param request * @param response * @return * @throws IOException */ @RequestMapping(value = "/sateImg") public String getSateImg(@RequestParam(value="imgName") String imgName, HttpServletRequest request,HttpServletResponse response) throws IOException { ServletOutputStream out = null; FileInputStream ips = null; try { //获取图片存放路径 String imgPath; if (isDebug.equals("true")) { URL dataUrl = this.getClass().getClassLoader().getResource("static/img/sate/sate.png"); ips = new FileInputStream(new File(dataUrl.toURI())); } else if(isDebug.equals("false")){ imgPath = dir +"/sate/"+TimeUtil.format(new Date(),"yyyyMMdd")+"/" +imgName+".png"; ips = new FileInputStream(new File(imgPath)); } response.setContentType("multipart/form-data"); out = response.getOutputStream(); //读取文件流 int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = ips.read(buffer)) != -1){ out.write(buffer,0,len); } out.flush(); logger.info("获取卫星图片"+imgName+"成功"); }catch (Exception e){ logger.error("获取卫星图片失败"); }finally { out.close(); ips.close(); } return null; }
前台:
/** * 加载卫星图层 */ function getSateLiteLayer() { if (sateLiteLayer == null) { var fileName = formatDate(new Date().getTime(),"ddHH") + "-" +Math.floor(new Date().getMinutes()/15); var imageUrl = 'rest/sateImg?imgName='+fileName; var bounds = [[-4.96, 50.02], [59.97, 144.97]]; sateLiteLayer = L.imageOverlay(imageUrl, bounds, {opacity: 0.8}); } return sateLiteLayer; }