当前位置: 代码迷 >> Web前端 >> svg安插中文名称的图片解决方案
  详细解决方案

svg安插中文名称的图片解决方案

热度:79   发布时间:2012-09-08 10:48:07.0
svg插入中文名称的图片解决方案
svg插入中文名称的图片解决方案
种种原因吧 ,程序中用了中文名称的图片,嵌入svg中,因为确实不能把这些图片搞成英文名称了,只好找个解决方案绕过去。
网上说可以改tomcat的server.xml配置 加入URIEncoding="UTF-8" ,如下
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>
这样写 直接访问http://localhost:8080/svgtest/bmp/按钮.png 倒是可以显示了,但svg中的图片还是不能显示。

解决方法:对中文名称进行encodeURI转码才行;
<?xml version="1.0" encoding="utf-8" standalone="no" ?>
<svg id="svgRoot" onload="init()" xmlns="http://www.w3.org/2000/svg" xmlns:cge="http://iec.ch/TC57/2005/SVG-schema#" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">
	<title>标题</title>
	<desc>SVG</desc>
	<script><![CDATA[
		function init(){
	  		var svgDoc = evt.target.ownerDocument;
	  		var root = svgDoc.documentElement; 
	  	    var imgs = root.getElementsByTagName("image");
	  	    for(var i=0;i<imgs.length;i++){
		  		var xlinkns = "http://www.w3.org/1999/xlink";
		  		var oldImg = imgs.item(i).getAttribute("xlink:href");//不要写成imgs[i]
		  		imgs.item(i).setAttributeNS(xlinkns,"xlink:href",encodeURI(oldImg)); 	  	    
	  	    }
	  		/*
	  		var img1 = root.getElementById("img1");
	  		var xlinkns = "http://www.w3.org/1999/xlink";
	  		var oldImg = img1.getAttribute("xlink:href");
	  		img1.setAttributeNS(xlinkns,"xlink:href",encodeURI(oldImg)); 
	  		*/

	  		//alert(imgs.item(0).getAttribute("xlink:href"));
		}
	 ]]></script>
	<image x="100" y="100" width="100" height="100" xlink:href="../bmp/anniu.png"/>
	<image id="img1" x="100" y="200" width="100" height="100" xlink:href="../bmp/按钮.png"/>
	<!--
	<image x="100" y="300" width="100" height="100" xlink:href="../bmp/%E6%8C%89%E9%92%AE.png"/>
	-->
</svg>

还有一点值得注意,就是遍历数组的时候不要写成xx[i],而应该写成item(i),网上竟然查到有人说getElementsByTagName方法是 svgviwer ie插件的bug(%>_<%),感谢武汉的小鱼帮忙。

=========
今天又测了下,确实必须修改tomcat的server.xml配置, 加入URIEncoding="UTF-8".
注意清除IE缓存
  相关解决方案