// 新增图片 if (ac.equals("imgadvaddold")) { try { String img = ""; String imgtype = ""; request.setCharacterEncoding("utf-8"); RequestContext requestContext = new ServletRequestContext( request); if (FileUpload.isMultipartContent(requestContext)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(request .getRealPath("/upfile/") + "/")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(100 * 1024 * 1024); List items = new ArrayList(); items = upload.parseRequest(request); imgtype = ((FileItem) items.get(1)).getString(); imgtype = Info.getUTFStr(imgtype); FileItem fileItem = (FileItem) items.get(0); if (fileItem.getName() != null && fileItem.getSize() != 0) { if (fileItem.getName() != null && fileItem.getSize() != 0) { File fullFile = new File(fileItem.getName()); img = Info.generalFileName(fullFile.getName()); File newFile = new File( request.getRealPath("/upfile/") + "/" + img); try { fileItem.write(newFile); } catch (Exception e) { e.printStackTrace(); } } else { } } } String cksql = "select * from imgadv where imgtype='banner'"; ArrayList cklist = (ArrayList) dao.select(cksql); if (imgtype.equals("banner") && cklist.size() != 0) { request.setAttribute("no", ""); go("/admin/imgadvadd.jsp", request, response); } else { String sql = "insert into imgadv (filename,imgtype) " + "values('" + img + "','" + imgtype + "')"; dao.commOper(sql); request.setAttribute("suc", ""); go("/admin/imgadvadd.jsp", request, response); } } catch (Exception e1) { e1.printStackTrace(); request.setAttribute("no", ""); request.getRequestDispatcher("/admin/imgadvadd.jsp").forward( request, response); } }
时间: 2024-04-27 16:23:04 浏览: 90
这是一个Java Servlet中的一段代码,用于处理上传图片的逻辑,包括获取上传的文件、文件类型,保存到指定目录,并将文件信息插入到数据库中。其中使用了Apache Commons FileUpload库来处理文件上传。在上传图片之前,会先检查数据库中是否已经存在同类型的图片,如果存在则不允许上传。
阅读全文