1:在jsp页面的代码如下:
<% //定义上载文件的最大字节 int MAX_SIZE = 102400 * 102400; // 创建根路径的保存变量 String rootPath; //声明文件读入类 DataInputStream in = null; FileOutputStream fileOut = null; String photo = null; //取得客户端的网络地址 String remoteAddr = request.getRemoteAddr(); //获得服务器的名字 String serverName = request.getServerName(); String serverAddress=request.getServletPath(); System.out.println("remoteAddr:" + remoteAddr + " serverName:" + serverName+"serverAddress:"+serverAddress); //取得互联网程序的绝对地址 String realPath = request.getRealPath(""); System.out.println("realPath:" + realPath); realPath = realPath.substring(0, realPath.lastIndexOf("\\")); //创建文件的保存目录 rootPath = "/Zhuxn/photos/"; SmartUpload upload = new SmartUpload(); upload.initialize(pageContext); upload.setMaxFileSize(MAX_SIZE); upload.setTotalMaxFileSize(MAX_SIZE); upload.setAllowedFilesList("jpg,jpeg,bmp,png"); try { upload.upload(); photo = rootPath + upload.getFiles().getFile(0).getFileName(); System.out.println("rootPath:" + rootPath); File fileDir = new File(rootPath); if (!fileDir.exists()) { fileDir.mkdirs(); } int count = upload.save(rootPath); System.out.println(count); } catch (Exception e) { e.printStackTrace(); %>说明:由于知识展示代码片段,可能会出现不能完整运行的问题。
2:上面的代码依靠了一个第三方的扩展包jspSmartUpload.jar,可以在网上下载。
3:在文件上传的前台界面的表单的form属性上,注意要添加enctype=”multipart/form-data”
以上则可以完成文件的上传,在这里展示的是上传图片。