common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/ 下载。
1)上传页面 upload.jsp
<!-- 上传必须要method="post" enctype="multipart/form-data" --> <form method="post" action="doUp2.jsp" name="frm" enctype="multipart/form-data"> <table border="0" width="342" height="136" align="center"> <tbody> <tr> <td> 说明:</td> <td> <input type="text" name="ucontent"> </td> </tr> <tr> <td> 照片1:</td> <td> <input type="file" name="pic1"> </td> </tr> <tr> <td> 照片2:</td> <td> <input type="file" name="pic2"> </td> </tr> <tr> <td> 照片3:</td> <td> <input type="file" name="pic3"> </td> </tr> <tr> <td> </td> <td><input type="submit" value="上传" name="button1"> <br> </td> </tr> </tbody> </table> <br> </form>2)处理页面 doUp2.jsp
<% //1.指定服务器的路径 //D:\apache-tomcat-8.0.12\webapps\jsp3_downup_20151230 String paths = request.getSession().getServletContext() .getRealPath("/upload"); System.out.println(paths); //2.创建文件夹 File file = new File(paths); //3.判断不存在,创建文件夹 if (!file.exists()) { file.mkdir(); } /** 3. * 首先判断form的enctype是不是multipart/form-data * 同时也判断了form的提交方式是不是post * 方法:isMultipartContent(request) */ if (ServletFileUpload.isMultipartContent(request)) { //4. 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); //5.创建ServletFileUpload对象 ServletFileUpload upload = new ServletFileUpload(factory); //////////////////////////////////// //设置单个文件最大值byte 100kb upload.setFileSizeMax(100 * 1024); //所有上传文件的总和最大值byte 160kb upload.setSizeMax(160 * 1024); ////////////////////////////////// //6.获得文件上传列表 List<FileItem> list = null; //保存上传的文件名 List<String> fileNames=new ArrayList<String>(); try { //文件列表允许上传的文件格式 List<String> types = Arrays.asList("jpg", "gif", "txt"); list = upload.parseRequest(request); //遍历数据 for (FileItem item : list) { //1.是否是普通字段 if (item.isFormField()) { System.out.println(item.getFieldName() + "=" + item.getString("utf-8")); } else { //上传文件名 String upFile = item.getName(); //Kaola.jpg///////////////// //取扩展名.jpg,.txt String ext = upFile.substring(upFile .lastIndexOf(".") + 1); //判断 if (!types.contains(ext)) { out.println("上传的文件《"+upFile+"》格式不正确!文件格式必须是" + types.toString()+"<p/>"); } else { //保存文件到集合中 fileNames.add(upFile); //////////////////////////////////////// //保存文件 // @param parent The parent abstract pathname //* @param child The child pathname string File saveFile = new File(file, upFile); //写入 item.write(saveFile); //查看 out.println(upFile + "的大小是:" + item.getSize() + "字节数!<p/>"); } } } //跳转 request.setAttribute("fileNames",fileNames); request.getRequestDispatcher("download.jsp").forward(request, response); } catch (FileUploadBase.SizeLimitExceededException ee0) { out.println("所有文件大小最大是:" + upload.getSizeMax() + "字节!"); } catch (FileSizeLimitExceededException ee1) { out.println("单个文件大小最大是:" + upload.getFileSizeMax() + "字节!"); } catch (FileUploadException ex) { ex.printStackTrace(); } } else { out.println("上传的格式属性不正确!"); } %>3)下载页面down.jsp
<br> --------------直接下载------------ <br> <% List<String> fileNames = (List<String> )request.getAttribute("fileNames"); for(String fileName : fileNames) { %> <form action="doDown.jsp" method="get"> <input type="hidden" name="fileName" value="<%=fileName %>" /> <input type="submit" value="下载:<%=fileName %>" /> </form> <% } %> <br> --------------直接打开--------- <% for(String fileName : fileNames) { %> <form action="doDown.jsp" method="get"> <input type="hidden" name="fileName" value="<%=fileName %>" /> <input type="hidden" name="online" value="yes" /> <input type="submit" value="打开:<%=fileName %>" /> </form> <% } %> </br>4)处理下载页面 doDown.jsp
<% //指定服务器路径 String fileDir = request.getSession().getServletContext() .getRealPath("/upload"); //中文处理 request.setCharacterEncoding("utf-8"); //表单请求的值 String aFileName = request.getParameter("fileName"); String online = request.getParameter("online"); //输入流 FileInputStream in = null; //输出流 ServletOutputStream outs = null; //判断是否占线 boolean isOnLine = online != null ? true : false; try { if (isOnLine) { URL u = new URL("file:///" + fileDir + aFileName); //设置头信息 response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + aFileName); } else { ///设置内容类型和头信息 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + aFileName); } in = new FileInputStream(fileDir + "\\" + aFileName); outs = response.getOutputStream(); outs.flush(); //读取 int aRead = 0; while ((aRead = in.read()) != -1 & in != null) { outs.write(aRead); //写入 } outs.flush(); //刷新 //发生异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response out.clear(); out = pageContext.pushBody(); /////////////////////////// } catch (Throwable e) { e.printStackTrace(); } finally { try { //关闭 in.close(); outs.close(); } catch (Throwable e) { e.printStackTrace(); } } %>总结:通过 common-fileupload 组件实现了上传和下载功能。
上传功能:可以上传一个或多个文件,可以控制单个上传文件的大小,也可以控制所有文件上传的总大小,还可以限制上传 文件的格式。
下载功能:可以直接下载,也可以直接打开内容。