文件上传中form表单的enctype="multipart/form-data" 为二进制文件传输,所在在后端无法用request.Parameter()方法进行获取表单参数。
之前文件上传考虑用SmartUpload组件进行上传,但是该组件对中文的支持不够,中文会乱码。所以将SmartUpload的源码进行修改并重新封装jar包,该jar包在对于UTF-8格式的JSP页面是好用的。链接如下:
https://download.csdn.net/download/weixin_38237873/10864957
但是由于现在做的系统是保险核心的老系统,页面都是GBK格式的,这个组件就不好用了,除非表单和文件名都是英文。所以选择了另外一种文件上传的方式:
DiskFileUpload
直接上代码:
/*获取保存路径这里配置的是我们项目服务器存储路径*/
String path = PubFun.getSysvarValue("savesqlpath");
String tFileName = "";
String applyName = "";
String description = "";
if(null == path||"".equals(path)){
System.out.println("保存路径不能为空!");
}else{
String[] tDate = mDate.split("-");
/*拼接路径*/
for(int i = 0;i<tDate.length;i++){
path = path +"/"+tDate[i];
}
System.out.println("服务器存储路径:"+path);
File newFile = new File(path);
if (!newFile.exists()&& !newFile .isDirectory()) { // 如果日期文件夹不存在,则创建
newFile.mkdirs();
}
DiskFileUpload fu = new DiskFileUpload();
//设置阀值大小
//不设置的话,默认10k
//超过这个阀值,FileItem将直接写入到磁盘
fu.setSizeThreshold(1024*10);
fu.setRepositoryPath(path);
fu.setHeaderEncoding("UTF-8");
try{
List items = fu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()){
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
//表单信息
String tName = item.getFieldName();
if("applyName".equals(tName)){
applyName = new String(item.getString().getBytes("iso-8859-1"),"GBK");
System.out.println("申请人姓名:"+applyName);
}else if ("description".equals(tName)){
description = new String(item.getString().getBytes("iso-8859-1"),"GBK");
System.out.println("运维问题描述:"+description);
}
}
if(!item.isFormField()){
//附件信息
//获取文件名称
tFileName = item.getName();
System.out.println("完整文件名:"+tFileName);
String tContent = new String(item.getString().getBytes("iso-8859-1"),"UTF-8");
System.out.println("文件内容为:"+tContent);
if(tFileName.indexOf("\\")>0){
String[] tempArr = tFileName.split("\\\\");
//获取截取后的文件名
tFileName = tempArr[tempArr.length-1];
System.out.println("截取后文件名:"+tFileName);
}
//保存文件
item.write(new File(path +"/"+ tFileName));
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("upload file error ...");
content = "上载文件出现异常!";
flagStr = "Fail";
return;
}
System.out.println("上传文件名称:"+tFileName);
}