最近忙着考试,没什么时间更新博客,下面说一下如何在servlet上实现文件的上传.
首先上传文件的表单的方法method="Post",编码方式enctype="multipart/form-data"(这个很重要),action="servlet的url"
如: html
<form action="FileUploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="upload" /> <input type="submit"/> </form>
咱们使用 Apache提供的commons-fileupload jar包实现文件上传 java
要导入的包:
FileUpload 1.3.jar http://commons.apache.org/proper/commons-fileupload/
commons-io-2.4.jar http://commons.apache.org/proper/commons-io/download_io.cgi
存放到lib目录下
FileUploadServlet的代码: apache
boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { //检查请求是否为multipart表单数据 return; } //请求正文的每一个子部分都被看做一个FileItem对象 // 建立一个基于硬盘的FileItem工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置缓冲区大小 factory.setSizeThreshold(1024); //设置临时目录 factory.setRepository(new File(tempPath)); //建立文件上传处理器 ServletFileUpload upload = new ServletFileUpload(factory); //设置文件的最大尺寸 以字节为单位 upload.setFileSizeMax(1024 * 1024 * 2); //解析请求正文 List<FileItem> fileitems =upload.parseRequest(req); // 遍历全部的FileItem对象 for (int i = 0; i < fileitems.size(); i++) { FileItem item = fileitems.get(i); // 整个表单的全部域都会被解析,要先判断一下是普通表单域仍是文件上传域 if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); System.out.println(name + ":" + value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMem = item.isInMemory(); long sizeInBytes = item.getSize(); System.out.println(req.getRemoteAddr() + "上传文件" + fileName); System.out.println(fieldName + ":" + fileName); System.out.println("类型:" + contentType); System.out.println("文件大小" + sizeInBytes); File uploadedFile = new File(filePath+ fileName); item.write(uploadedFile); } } post