我在我的Android应用程序中使用NanoHTTPD作为Web服务器,我使用代码A将多个文件包含中文文件名到服务器客户端。
但是我在代码B中得到了中文文件名的乱码,我该如何解决这个问题呢?谢谢!
凌乱的代码截图
代码A
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WiFi File Transfer</title>
<meta charset= "utf-8"/>
</head>
<body>
<div id="content">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myupload" multiple="multiple" />
<input type="submit" value="Upload Files"/>
</form>
</div>
</body>
</html>
代码B
@Override
public Response serve(IHTTPSession session) {
String uri = session.getUri();
MURLPar mURLPar=new MURLPar(mContext);
SetMURLParValue(mURLPar,session);
Method method = session.getMethod();
if (Method.POST.equals(method)) {
Map<String, String> files=null;
try {
files = new HashMap<String, String>();
session.parseBody(files);
}catch (Exception e) {
}
ActionUploadFiles(mURLPar,files,session);
...
}
private void ActionUploadFiles(MURLPar mURLPar, Map<String, String> files,IHTTPSession session){
File upload = new File(FileFolderHelper.GetPhysicsCurrentPath(mURLPar) +"/Upload");
try{
Set<String> keys = files.keySet();
for (String key:keys) {
String location = files.get(key);
File source = new File(location);
String filename=session.getParms().get(key);
//It will be messy code when uploaded filename is chinese!
filename=java.net.URLDecoder.decode(filename, "utf-8");
File target = new File(upload.getPath(),filename);
FileUtils.copyFile(source,target);
}
}
catch (Exception e) {
Utility.LogError("Upload Error: "+ e.getMessage());
}
}
答案 0 :(得分:5)
文件名不是URL编码的。 NanoHTTPD在Content-Type
标头中查找charset
指令。
不幸的是,似乎multipart/form-data
唯一有效的指令是boundary
,
和NanoHTTPD回归ASCII。
除了修改NanoHTTPD ContentType.getEncoding()
方法之外,我能想到的唯一解决方法是:
添加accept-charset="UTF-8"
以确保表单编码。
<div id="content">
<form action="" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
<input type="file" name="myupload" multiple="multiple" />
<input type="submit" value="Upload Files"/>
</form>
在解析内容之前将charset指令添加到NanoHTTPD会话中,ContentType
类有一个完全符合的方法:
@Override
public Response serve(IHTTPSession session) {
// add "; charset=UTF-8" to the content type
ContentType ct = new ContentType(session.getHeaders().get("content-type")).tryUTF8();
session.getHeaders().put("content-type", ct.getContentTypeHeader());
...
// no need to URL decode
String filename=session.getParms().get(key);