你可以试着引入jspsmart.upload这个工具来实现文件上传,比较方便。
action的写法:
//新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 上传初始化
su.initialize(getServlet().getServletConfig(),request,response);
// 设定上传限制
// 1.限制每个上传文件的最大长度。
su.setMaxFileSize(30000);
// 2.限制总上传数据的长度。
su.setTotalMaxFileSize(30000);
// 3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
su.setAllowedFilesList("doc,txt"
;
// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。
try {
su.setDeniedFilesList("exe,bat,jsp,htm,html"
;
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 上传文件
su.upload();
// 将上传文件全部保存到指定目录
String folder = "jie";//保存文件的文件夹名
String filePath = "/"+folder+"/";
//String filePath = "/192.168.0.66/D:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/"+folder+"/";//取当前系统路径
//String filePath = "\\\192.168.0.66\\"+folder+"\\";//取当前系统路径
java.io.File myFilePath=new java.io.File(filePath);
if(!myFilePath.exists()){
System.out.println("创建文件夹,myFilePath:"+filePath);
myFilePath.mkdir();
}
System.out.println("取当前系统路径:"+filePath);
// 利用Request对象获取参数之值
System.out.println("TEST="+su.getRequest().getParameter("TEST"
);
// 逐一提取上传文件信息,同时可保存文件。
com.jspsmart.upload.File file = su.getFiles().getFile(0);
//显示当前文件信息
System.out.println("文件长度(Size):"+
file.getSize());
System.out.println("文件名(FileName):" +file.getFileName());
System.out.println("文件扩展名(FileExt):"+file.getFileExt());
System.out.println("文件全名(FilePathName):"+file.getFilePathName());
su.save(filePath);//上传文件
//su.uploadInFile(filePath);
// 将文件改名另存(D盘下)
String newFileName = "jessiexxb."+file.getFileExt();
file.saveAs(filePath+newFileName);
//file.saveAs(filePath+file.getFieldName());
jsp页面:
上传:
这样就可以实现文件上传了。
|