标签:pattern trace lte jsp request 就会 iter java indexof
文件上传
使用commons-fileupload-1.4控件及依赖的commons-io-2.6控件
jsp页面中内容
servlet
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 response.setContentType("text/html;charset=utf-8"); 4 PrintWriter out = response.getWriter(); 5 // Create a factory for disk-based file items 6 DiskFileItemFactory factory = new DiskFileItemFactory(); 7 // Configure a repository (to ensure a secure temp location is used) 8 ServletContext servletContext = this.getServletConfig().getServletContext(); 9 File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); 10 factory.setRepository(repository); 11 // Create a new file upload handler 12 ServletFileUpload upload = new ServletFileUpload(factory); 13 upload.setHeaderEncoding("utf-8"); 14 // Parse the request 15 String saveName = ""; 16 try { 17 List<FileItem> items = upload.parseRequest(request); 18 for (FileItem item : items) { 19 if(item.isFormField()){//如果只是表单中信息,不是表单文件 20 String fieldName = item.getFieldName(); 21 String fieldValue = item.getString(); 22 out.print("<br>fieldName: "+fieldName+",--fieldValue: "+fieldValue); 23 }else{ 24 InputStream inputStream = item.getInputStream(); 25 //得到保存文件的路径 26 String realpath=this.getServletContext().getRealPath("update"); 27 //得到上传的文件的名字,可能显示的是路径,所以需要取出文件名 28 String allFilePath = item.getName(); 29 //getName()值为绝对路径!!!下面代码转换取文件名 30 String fileName = null; 31 int ind = allFilePath.lastIndexOf("\\"); 32 if (ind != -1) { 33 fileName = allFilePath.substring(ind + 1); 34 }else { 35 fileName = allFilePath; 36 } 37 38 out.print("<br>上传的文件名: "+fileName); 39 //读取的不能是目录,应该加上文件名 40 File file=new File(realpath + "\\" + fileName); 41 if(file.getParentFile().exists()){ 42 file.createNewFile();//创建文件 43 }else { 44 file.getParentFile().mkdirs();//创建父级文件路径 45 file.createNewFile();//创建文件 46 } 47 FileOutputStream fos=new FileOutputStream(file); 48 byte[] bytes= new byte[1024]; 49 int len=0; 50 //写入文件 51 while((len=inputStream.read(bytes))!=-1){ 52 fos.write(bytes, 0, len); 53 } 54 55 inputStream.close(); 56 fos.close(); 57 out.print("<h3>"+allFilePath+"文件上传成功</h3>"); 58 } 59 } 60 61 62 } catch (FileUploadException e) { 63 e.printStackTrace(); 64 } catch (FileNotFoundException e) { 65 e.printStackTrace(); 66 System.out.println(saveName); 67 } 68 }
web.xml
标签:pattern trace lte jsp request 就会 iter java indexof
原文地址:https://www.cnblogs.com/puhc/p/10666552.html