标签:exception for ota put get apache sre dba private
1、引入需要的两个jar包,commons-fileupload.jar 和 commons-io.jar
commons-fileupload.jar下载地址:
https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
commons-io.jar下载地址:
https://mvnrepository.com/artifact/commons-io/commons-io
将下好的jar包添加到web模块下的 WEB-INF/lib目录下
2.编写jsp页面
注意事项:1.form表单提交方式必须是post,因为上传文件一般都比较大
2.form表单属性必须要加上 enctype
=
"multipart/form-data"
3.input 框的type属性必须是file
4.action需提交给servlet,交由servlet上传到服务器的指定目录位置
3.编写servlet,继承HttpServlet,并重写deGet和doPost方法
1 package servlet; 2 3 import org.apache.tomcat.util.http.fileupload.*; 4 import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 5 import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 6 import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import java.io.File; 14 import java.io.FileOutputStream; 15 import java.io.IOException; 16 import java.io.InputStream; 17 import java.util.Calendar; 18 import java.util.Iterator; 19 import java.util.List; 20 import java.util.UUID; 21 22 /** 23 * 处理文件上传 24 * 25 **/ 26 @WebServlet("/UploadServlet") 27 public class UploadServlet extends HttpServlet { 28 @Override 29 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 30 //设置文件上传基本路径 31 String savePath = this.getServletContext().getRealPath("/WEB-INF/uploadFiles"); 32 //设置临时文件路径 33 String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempFiles"); 34 File tempFile = new File(tempPath); 35 if (!tempFile.exists()) { 36 tempFile.mkdir(); 37 } 38 39 //定义异常消息 40 String errorMessage = ""; 41 //创建file items工厂 42 DiskFileItemFactory factory = new DiskFileItemFactory(); 43 //设置缓冲区大小 44 factory.setSizeThreshold(1024 * 100); 45 //设置临时文件路径 46 factory.setRepository(tempFile); 47 //创建文件上传处理器 48 ServletFileUpload upload = new ServletFileUpload(factory); 49 //监听文件上传进度 50 ProgressListener progressListener = new ProgressListener() { 51 public void update(long pBytesRead, long pContentLength, int pItems) { 52 System.out.println("正在读取文件: " + pItems); 53 if (pContentLength == -1) { 54 System.out.println("已读取: " + pBytesRead + " 剩余0"); 55 } else { 56 System.out.println("文件总大小:" + pContentLength + " 已读取:" + pBytesRead); 57 } 58 } 59 }; 60 upload.setProgressListener(progressListener); 61 62 //解决上传文件名的中文乱码 63 upload.setHeaderEncoding("UTF-8"); 64 //判断提交上来的数据是否是上传表单的数据 65 if (!ServletFileUpload.isMultipartContent(request)) { 66 //按照传统方式获取数据 67 return; 68 } 69 70 //设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB 71 upload.setFileSizeMax(1024 * 1024); 72 //设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB 73 upload.setSizeMax(1024 * 1024 * 10); 74 75 try { 76 //使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项 77 List<FileItem> items = upload.parseRequest(new ServletRequestContext(request)); 78 Iterator<FileItem> iterator = items.iterator(); 79 while (iterator.hasNext()) { 80 FileItem item = iterator.next(); 81 82 //判断jsp提交过来的是不是文件 83 if (item.isFormField()) { 84 errorMessage = "请提交文件!"; 85 break; 86 } else { 87 //文件名 88 String fileName = item.getName(); 89 90 if (fileName == null || fileName.trim() == "") { 91 System.out.println("文件名为空!"); 92 } 93 //处理不同浏览器提交的文件名带路径问题 94 fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); 95 //文件扩展名 96 String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); 97 //判断扩展名是否合法 98 if (!validExtension(fileExtension)) { 99 errorMessage = "上传文件非法!"; 100 item.delete(); 101 break; 102 } 103 //获得文件输入流 104 InputStream in = item.getInputStream(); 105 //得到文件保存路径 106 String realFilePath = createRealFilePath(savePath, fileName); 107 System.out.println(realFilePath); 108 //创建文件输出流 109 FileOutputStream out = new FileOutputStream(realFilePath); 110 //创建缓冲区 111 byte buffer[] = new byte[1024]; 112 int len = 0; 113 while ((len = in.read(buffer)) > 0) { 114 //写文件 115 out.write(buffer, 0, len); 116 } 117 //关闭输入流 118 in.close(); 119 //关闭输出流 120 out.close(); 121 //删除临时文件 TODO 122 item.delete(); 123 //将上传文件信息保存到附件表中 TODO 124 } 125 126 } 127 128 } catch (FileUploadBase.FileSizeLimitExceededException e) { 129 e.printStackTrace(); 130 request.setAttribute("errorMessage", "单个文件超出最大值!!!"); 131 request.getRequestDispatcher("jsp/demo03.jsp").forward(request, response); 132 return; 133 } catch (FileUploadBase.SizeLimitExceededException e) { 134 e.printStackTrace(); 135 request.setAttribute("errorMessage", "上传文件的总的大小超出限制的最大值!!!"); 136 request.getRequestDispatcher("jsp/demo03.jsp").forward(request, response); 137 return; 138 } catch (FileUploadException e) { 139 e.printStackTrace(); 140 request.setAttribute("errorMessage", "文件上传失败!!!"); 141 request.getRequestDispatcher("jsp/demo03.jsp").forward(request, response); 142 return; 143 } 144 145 request.setAttribute("errorMessage", errorMessage); 146 request.getRequestDispatcher("jsp/demo03.jsp").forward(request, response); 147 148 149 } 150 151 @Override 152 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 153 doGet(request, response); 154 } 155 156 private boolean validExtension(String fileExtension) { 157 String[] exts = {"jpg", "txt", "doc", "pdf"}; 158 for (int i = 0; i < exts.length; i++) { 159 if (fileExtension.equals(exts[i])) { 160 return true; 161 } 162 163 } 164 165 return false; 166 } 167 168 // private String createFileName(String fileName) { 169 // return UUID.randomUUID().toString() + "_" + fileName; 170 // } 171 172 /** 173 * 根据基本路径和文件名称生成真实文件路径,基本路径\\年\\月\\fileName 174 * 175 */ 176 private String createRealFilePath(String basePath, String fileName) { 177 Calendar today = Calendar.getInstance(); 178 String year = String.valueOf(today.get(Calendar.YEAR)); 179 String month = String.valueOf(today.get(Calendar.MONTH) + 1); 180 181 182 String upPath = basePath + File.separator + year + File.separator + month + File.separator; 183 File uploadFolder = new File(upPath); 184 if (!uploadFolder.exists()) { 185 uploadFolder.mkdirs(); 186 } 187 188 String realFilePath = upPath + fileName; 189 190 return realFilePath; 191 } 192 }
4.运行Tomcat,打开jsp页面并上传文件,由于servlet方法中有限制文件格式,所以只能上传.jpg、.txt、.doc、.pdf文件,当然也可以不设置文件格式
jsp页面效果:
上传后若没有提示信息则上传成功,然后找到工程下的WEB-INF/uploadFiles文件夹,查看已上传的文件
这里必须通过绝对路径打开该文件夹才能看到上传后的文件信息,直接在工程里是看不到上传的文件内容的
简单的文件上传完成,看下我的工程目录(包建的很随意)
标签:exception for ota put get apache sre dba private
原文地址:https://www.cnblogs.com/zeng1997/p/11631991.html