swfupload 是flash和Javascript结合的一款文件上传控件,不同的公司在使用时有着不同的封装。解决文件上传时中文文件名乱码的问题,可想到的思路有2个:
1、通过在Java端设置或转换接收到的文件名字符。 这种方式较难操作,测试了多种不同类型间的编码转换,均未能正确转出。而且转码不能保证完全转码正确。
参考:http://blog.csdn.net/ycs0501/article/details/6994584
2、通过增加上传参数,将文件名使用encodeURIComponent()进行编码,在Java端接收后进行解码。这种方式稳定可靠。
关键点是要找准swfupload控件的方法,在发送前,加入文件名参数。见下例:
fileupload1.on('beforeupload', function(file){
this.setPostParam({fileName: encodeURIComponent(this.text) });
});
注意事项:
(1)上传控件发送前添加参数的事件不一定相同,有的叫onUploadStart,有的叫beforeupload,一定要找准。
(2)参数的设置方法是一个对象{fileName:encodeURIComponent(this.text)},不能使用串:this.setPostParam('fileName', encodeURIComponent(this.txt))。
服务端解码:
String fileName;
if (item.isFormField()) {
String fieldName = item.getFieldName();
if (fieldName.equals("fileName")) {
String fileNameValue = item.getString();
fileName = URLDecoder.decode(fileNameValue, "UTF-8");
System.out.println("fileName2:" + fileName);
}
}
服务端解码POST上来的 "fileName"字段,使用URLDecodere.decode()进行解码,就可以得到编码正确的中文文件名。