2.5 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--通过表单上传文件; get:上传文件大小有限制 post:上传文件大小没有限制 ${pageContext.request.contextPath}获取服务器当前路径 --%> <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post"> 上传用户:<input type="text" name="username"><br/> <p><input type="file" name="file1"></p> <p><input type="file" name="file1"></p> <p><input type="submit"> | <input type="reset"></p> </form> </body> </html>
2.6 info.jsp
该页面主要用于接受message
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%=request.getAttribute("msg")%> </body> </html>
2.7 FileServlet
这里的包一定要注意不要导错了。另外这里使用了封装的方法让结构看起来更简洁
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.UUID; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //判断上传的文件是普通表单还是带文件的表单 if (!ServletFileUpload.isMultipartContent(req)) { return;//终止方法运行,说明这是一个普通的表单 } //创建上传文件的保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件 //获得全局的上下文,地址 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdir();//创建这个目录 } //缓存,临时文件 //临时文件,假如文件超过了预期的大小,我们就把他放到一个临时文件中,过几天激动删除,或者提醒用户转存为永久 String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdir();//创建这个目录 } //处理上传的文件,一般需要通过流来获取,我们可以使用request.getInputStream(),原生态的文件上传流获取, //上面的太麻烦,建议使用APache的文件上传组件来实现,common-fileupload,它需要依赖于commons-io组件 try { //1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制的 DiskFileItemFactory factory = getDiskFileItemFactory(tmpFile); //2.获取ServletFileUpload ServletFileUpload upload = getServletFileUpload(factory); //3.处理上传文件 String msg = uploadParseRequest(upload, req, uploadPath); //servlet请求转发消息 req.setAttribute("msg", msg); req.getRequestDispatcher("info.jsp").forward(req, resp); } catch (FileUploadException e) { e.printStackTrace(); } } public static DiskFileItemFactory getDiskFileItemFactory(File tmpFile) { DiskFileItemFactory factory = new DiskFileItemFactory(); //通过这个工厂设置一个缓冲区,当上传的文件大于这个缓冲区的时候,将他放到临时文件中 //可以设可以不设 factory.setSizeThreshold(1024 * 1024); factory.setRepository(tmpFile); return factory; } public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) { //2.获取ServletFileUpload ServletFileUpload upload = new ServletFileUpload(factory); //可以设,可以不设 //监听文件上传进度 upload.setProgressListener(new ProgressListener() { //pContentLength:文件大小 //pBytesRead:已经读取到的文件大小 @Override public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("总大小:" + pContentLength + "已上传" + pBytesRead); } }); //处理乱码问题 upload.setHeaderEncoding("UTF-8"); //设置单个文件的最大值 upload.setFileSizeMax(1024 * 1024 * 10); //设置总共能够上传的文件的大小 //1024 = 1kb * 1024 = 1M * 10 = 10M upload.setSizeMax(1024 * 1024 * 10); return upload; } public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException { String msg = ""; //3.处理上传文件 //把前端请求解析,封装成一个FileItem对象,需要从ServletFileUpload对象中获取 List<FileItem> fileItems = upload.parseRequest(req); //每一个表单对象 for (FileItem fileItem : fileItems) { //判断上传的文件是普通的表单还是带文件的表单 if (fileItem.isFormField()) { //getFieldName()指的是前端表单控件的name String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8");//处理乱码 System.out.println(name + ":" + value); } else { //文件的情况 //=====处理文件 //拿到文件名字 String uploadFileName = fileItem.getName(); System.out.println("上传的文件名:" + uploadFileName); if (uploadFileName.trim().equals("") || uploadFileName == null) { continue; } //获得文件上传的文件名和后缀名;/images/boys/dajie.jpg 下面这块不是必须的 String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1); String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1); //如果文件后缀名fileExtName不是我们所需要的就直接return,不处理,告诉用户文件类型不对 System.out.println("文件信息【件名:" + fileName + "---文件类型" + fileExtName + "】"); //可以使用UUID(唯一识别的通用码),保证文件名唯一 //UUID.randomUUID(),随机生成一个唯一识别的通用码 //网络传输中的东西,都需要序列化, //比如:POJO,实体类,如果想要在多个电脑上运行,需要进行传输===>需要把对象序列化 //implements Serializable :标记接口,JVM--> java栈 本地方法栈 ; native---》C++ String uuidPath = UUID.randomUUID().toString(); //===处理文件结束 //=====存放地址 //存到哪?uploadPath //文件真实存在的路径realPath String realPath = uploadPath + "/" + uuidPath; //给每个文件创建一个对应的文件夹 File realPathFile = new File(realPath); if (!realPathFile.exists()) { realPathFile.mkdir(); } //=====存放地址完毕 //=====文件传输 //获得文件上传的流 InputStream inputStream = fileItem.getInputStream(); //创建一个文件输出流 //realPath = 真实的文件夹 //差了一个文件,加上输出的文件的名字+"/" +uuidFileName FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); //创建一个缓冲区 byte[] buffer = new byte[1024 * 1024]; //判断是否读取完毕 int len = 0; //如果大于0说明还存在数据 while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } //关闭流 fos.close(); inputStream.close(); msg = "文件上传成功!"; fileItem.delete();//上传成功,清楚临时文件 } } return msg; } }
2.8 配置Servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>com.hxl.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping> </web-app>
2.9 测试结果