在 Cordova/Phonegap for Android 中包含中文文件名的页面
本贴首发于:
http://xuekaiyuan.com/forum.php?mod=viewthread&tid=14
将中文文件名重命名为 jarsigner 程序支持的文件名
将文件名按 UTF-8 编码进行 URL 编码。
$encodename = urlencode(iconv('GB2312','UTF-8',$filename));
判断是否和原来的文件名相同
if ($encodename !== $filename) {
如果不相同则重命名
rename($argv[1] . DIRECTORY_SEPARATOR . $filename, $argv[1] . DIRECTORY_SEPARATOR . $encodename);
完整 rename.php 源代码如下
<?php foreach(scandir($argv[1]) as $filename) { $encodename = urlencode(iconv('GB2312','UTF-8',$filename)); if ($encodename !== $filename) { rename($argv[1] . DIRECTORY_SEPARATOR . $filename, $argv[1] . DIRECTORY_SEPARATOR . $encodename); echo 'rename ' . $filename . ' to ' . $encodename . " "; } } ?>
在程序中将请求还原成相应的文件名
确定需要判断的路径
String urlprefix = "file:///android_asset/www/";
判断当前请求是否属于该路径
if (url.startsWith(urlprefix)) {
属于该路径时,判断当前请求是否包含参数
if (url.contains("?") || url.contains("#")) {
获取文件路径
String relativePath = "www/" + url.substring(urlprefix.length());
尝试按路径打开文件
stream = cordova.getActivity().getAssets().open(relativePath);
不能打开文件时,返回异常信息作为文件内容
StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter, true); e.printStackTrace(printWriter); byte[] bytes = new byte[0]; try { bytes = stringWriter.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } stream = new ByteArrayInputStream(bytes);
获取文件的 MIME 类型
String mimetype = FileHelper.getMimeType(url, cordova);
返回该文件
return new WebResourceResponse(mimetype, "UTF-8", stream);
完整 UrlFilter.java 源代码如下
public WebResourceResponse shouldInterceptRequest(String url) { String urlprefix = "file:///android_asset/www/"; if (url.startsWith(urlprefix)) { if (url.contains("?") || url.contains("#")) { return super.shouldInterceptRequest(url); } else { String relativePath = "www/" + url.substring(urlprefix.length()); InputStream stream; try { stream = cordova.getActivity().getAssets().open(relativePath); } catch (IOException e) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter, true); e.printStackTrace(printWriter); byte[] bytes = new byte[0]; try { bytes = stringWriter.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } stream = new ByteArrayInputStream(bytes); } String mimetype = FileHelper.getMimeType(url, cordova); return new WebResourceResponse(mimetype, "UTF-8", stream); } } else { return super.shouldInterceptRequest(url); } }
在虚拟机中的效果如图所示