网上相册(上传与下载)
2016-07-24 00:04
274 查看
运用apache解析工具实现网上相册
主页:
servlet处理:
上传:
保存数据:
显示图片:
界面显示:
删除图片:
dom单例对象
数据保存入xml
数据删除于xml
xml读取数据封装值对象
值对象:
map解析成值对象的beanutil
主页:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>文件上传</title> <script type="text/javascript"> onload=function(){ var msg=document.getElementsByName("msg").item(0); if(msg.value=="noGet"){ alert("文件不支持get方式提交"); }else if(msg.value=="noFile"){ alert("请选择文件"); }else if(msg.value=="noMultipart"){ alert("不支持普通表单提交"); }else if(msg.value=="true"){ alert("上传成功"); }else if(msg.value=="false"){ alert("上传失败"); } }; </script> </head> <body> <form action="uploadFileServlet" method="post" enctype="multipart/form-data"> <table> <tr><td><input type="file" name="file"/></td></tr> <tr><td><textarea rows="10" cols="20" title="文件说明" name="fileMsg"></textarea></td></tr> <tr><td><input type="submit" value="上传"/></td></tr> </table> </form> <input type="hidden" value="<%=request.getParameter("msg")%>" name="msg"/> <a href="showImageServlet">查看个人上传画册</a> <a href="showAllImageServlet">查看所有图片</a> </body> </html>
servlet处理:
上传:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("index.jsp?msg=noGet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(!ServletFileUpload.isMultipartContent(request)){ response.sendRedirect("index.jsp?msg=noMultipart"); return; } request.setCharacterEncoding("utf-8"); String pathname=getServletContext().getRealPath("/images/uploadImg"); File filePath=new File(pathname); if(!filePath.exists()){ filePath.mkdirs(); } DiskFileItemFactory factory=new DiskFileItemFactory(); factory.setSizeThreshold(1024*8); factory.setRepository(filePath); ServletFileUpload upload=new ServletFileUpload(factory); long fileSizeMax=1024*1024*2; upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(fileSizeMax*10); FileItem itemClose=null; try { List<FileItem> list=upload.parseRequest(request); if(list.size()==0){ response.sendRedirect("index.jsp?msg=noFile"); return; } String fileMsg=null; String filepath=null; String fileName=null; String newFileName=null; String fileUploadTime=null; for(FileItem item:list){ itemClose=item; if(item.isFormField()){ fileMsg=item.getString("utf-8"); }else{ if(item.getSize()==0){ response.sendRedirect("index.jsp?msg=noFile"); return; } fileName=item.getName();//上传文件名 int index=fileName.lastIndexOf("."); String ext=fileName.substring(index); String fileIdName=UUID.randomUUID().toString().replace("-", ""); newFileName=fileIdName+ext;//新文件名 int hash=fileName.substring(0, index).hashCode(); String fileDirPath=""+Integer.toHexString(hash&0xf)+"/"+Integer.toHexString((hash&0xf0)>>4); pathname+="/"+fileDirPath;//存放文件目录 File file=new File(pathname); if(!file.exists()){ file.mkdirs(); } File newfile=new File(pathname+"/"+newFileName); item.write(newfile); DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); fileUploadTime=df.format(new Date(newfile.lastModified())); filepath=newfile.getAbsolutePath().substring(newfile.getAbsolutePath().indexOf(request.getContextPath().replace("/", "\\"))).replace("\\", "/"); } } request.setAttribute("userName", request.getRemoteAddr()); request.setAttribute("fileName", fileName); request.setAttribute("newFileName", newFileName); request.setAttribute("filepath", filepath); request.setAttribute("fileMsg", fileMsg); request.setAttribute("fileUploadTime", fileUploadTime); request.getRequestDispatcher("/saveFileMsgServlet").forward(request, response); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ if(itemClose!=null) itemClose.delete(); } }
保存数据:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String userName=(String)request.getAttribute("userName"); String fileName=(String) request.getAttribute("fileName"); String newFileName=(String) request.getAttribute("newFileName"); String filepath=(String) request.getAttribute("filepath"); String fileMsg=(String) request.getAttribute("fileMsg"); String fileUploadTime=(String)request.getAttribute("fileUploadTime"); //System.out.println(fileName+","+newFileName+","+filepath+","+fileMsg); String[] elementName=new String[]{"fileName","fileUploadTime","newFileName","filepath","fileMsg"}; String[] elementText=new String[]{fileName,fileUploadTime,newFileName,filepath,fileMsg}; if(Dom4jSaveFileMsg.SaveElement("userName",elementName,userName, elementText)) response.sendRedirect("index.jsp?msg=true"); else response.sendRedirect("index.jsp?msg=false"); }
显示图片:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getRemoteAddr(); List<ImageModel> imgList=ImageForXML.getCurrentUserImages(userName); // for(ImageModel img:imgList){ // System.out.println(img); // } request.setAttribute("imgList", imgList); request.getRequestDispatcher("/jsp/showImg.jsp?source=SingleUser&judge="+request.getParameter("del")).forward(request, response); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<ImageModel> imgList=ImageForXML.getAllImages(); // for(ImageModel img:imgList){ // System.out.println(img); // } request.setAttribute("imgList", imgList); request.getRequestDispatcher("/jsp/showImg.jsp?source=AllUser&judge="+request.getParameter("del")).forward(request, response); }
界面显示:
<%@page import="cn.hncu.uploadFile.vo.ImageModel"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>图片展示</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <style type="text/css"> table{ width: 60%; } td{ border: solid blue 2px; } img{ width: 300px; height: 200px; } </style> <script type="text/javascript"> onload=function(){ var source=document.getElementsByName("source").item(0); if(source.value=="noUser"){ alert("您对于该图片不具有删除权限") }else if(source.value=="ok"){ alert("删除图片成功") }else if(source.value=="noDel"){ alert("删除图片失败") } }; </script> </head> <body> <table> <tr><th>图片名</th><th>上传时间</th><th>图片</th><th>图片说明</th><th>操作</th></tr> <% List<ImageModel> imgList =(List<ImageModel>)request.getAttribute("imgList"); for(ImageModel img:imgList){%> <tr> <td><%=img.getFileName()%></td> <td><%=img.getFileUploadTime()%></td> <td><a href="<%=img.getFilepath()%>"><img src="<%=img.getFilepath()%>"></a></td> <td><%=img.getFileMsg()%></td> <td><a href="delImgServlet?imgId=<%=img.getId() %>&source=<%=request.getParameter("source") %>">删除</a> <a href="downImageServlet?imgId=<%=img.getId() %>">下载</a></td> </tr> <%} %> </table> <a href="showAllImageServlet">查看所有图片</a> <a href="showImageServlet">查看个人图片</a> <input type="hidden" value="<%=request.getParameter("judge") %>" name="source"> </body> </html>
删除图片:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id=request.getParameter("imgId"); ImageModel img=ImageForXML.getSingleImageById(id); if(!request.getRemoteAddr().equals(img.getUserName())){ request.getRequestDispatcher("/showAllImageServlet?del=noUser").forward(request, response); }else{ String source=request.getParameter("source"); if(Dom4jDelFileMsg.delFileForXML(id)){ String name=request.getContextPath(); File file=new File(request.getServletContext().getRealPath(img.getFilepath().substring(name.length()))); if(file.delete()){ if("SingleUser".equals(source)) request.getRequestDispatcher("/showImageServlet?del=ok").forward(request, response); else if("AllUser".equals(source)) request.getRequestDispatcher("/showAllImageServlet?del=ok").forward(request, response); return; } } if("SingleUser".equals(source)) request.getRequestDispatcher("/showImageServlet?del=noDel").forward(request, response); else if("AllUser".equals(source)) request.getRequestDispatcher("/showAllImageServlet?del=noDel").forward(request, response); } }下载图片:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id=request.getParameter("imgId"); ImageModel img=ImageForXML.getSingleImageById(id); response.setContentType("application/force-download"); response.setCharacterEncoding("utf-8"); String fileName=img.getFileName(); if(request.getHeader("user-agent").contains("Firefox"))//判断是否为火狐 fileName=new String(fileName.getBytes("utf-8"), "ISO8859-1"); else fileName=URLEncoder.encode(fileName, "utf-8"); response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\""); String name=request.getContextPath(); File file=new File(request.getServletContext().getRealPath(img.getFilepath().substring(name.length()))); OutputStream out=response.getOutputStream(); byte[] buf=new byte[1024]; FileInputStream fin=new FileInputStream(file); int len=0; while((len=fin.read(buf))!=-1){ out.write(buf, 0, len); } fin.close();out.flush();out.close(); }所用的工具类:
dom单例对象
public class DOMFactory { private static Document dom; private static String fileName; static{ String name=DOMFactory.class.getSimpleName()+".class"; String packageName=DOMFactory.class.getPackage().getName().replace(".", "/"); String urlPath=DOMFactory.class.getResource(name).getPath(); String path=urlPath.substring(0, urlPath.lastIndexOf(packageName)); fileName=path+"uploadFileMsg.xml"; File file=new File(fileName); if(!file.exists()){ try { file.createNewFile(); FileWriter pw=new FileWriter(file); pw.write("<?xml version='1.0' encoding='utf-8'?>"); pw.flush(); pw.close(); dom=DocumentHelper.createDocument(); dom.addElement("Files"); SaveDom(); } catch (IOException e) { e.printStackTrace(); } } SAXReader sax=new SAXReader(); try { dom=sax.read(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } } public static Document getInstance(){ return dom; } public static boolean SaveDom() { OutputFormat format=OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter w=null; try { w=new XMLWriter(new FileOutputStream(fileName),format); w.write(dom); return true; } catch (IOException e) { e.printStackTrace(); }finally{ if(w!=null) try { w.close(); } catch (IOException e) { e.printStackTrace(); } } return false; } }
数据保存入xml
public static boolean SaveElement(String attName, String[] elementName, String userName, String[] elementText) { Document dom=DOMFactory.getInstance(); Element ele=dom.getRootElement().addElement("file"); ele.addAttribute("id", UUID.randomUUID().toString().replace("-", "")); if(userName!=null) ele.addAttribute(attName, userName); for(int i=0;i<elementName.length;i++){ ele.addElement(elementName[i]).setText(elementText[i]); } return DOMFactory.SaveDom(); }
数据删除于xml
private static Document dom=DOMFactory.getInstance(); public static boolean delFileForXML(String id){ return delFile("//file[@id='"+id+"']"); } private static boolean delFile(String xpth){ Element e=(Element) dom.selectSingleNode(xpth); if(!e.getName().equals("file")) return false; else{ if(e.getParent().remove(e)) return DOMFactory.SaveDom(); return false; } }
xml读取数据封装值对象
public class ImageForXML { private static Document dom=DOMFactory.getInstance(); private static ImageModel getSingleImage(String xpth){ Element e=(Element) dom.selectSingleNode(xpth); if(!e.getName().equals("file")) return null; Map<String, String> map=new HashMap<String, String>(); map.put("id", e.attributeValue("id")); map.put("userName", e.attributeValue("userName")); map.put("fileUploadTime", e.elementText("fileUploadTime")); map.put("fileName", e.elementText("fileName")); map.put("newFileName", e.elementText("newFileName")); map.put("filepath", e.elementText("filepath")); map.put("fileMsg", e.elementText("fileMsg")); return BeanUtil.getInstance(ImageModel.class, map); } public static ImageModel getSingleImageById(String id){ return getSingleImage("//file[@id='"+id+"']"); } public static List<ImageModel> getCurrentUserImages(String userName){ String xpath="//file[@userName='"+userName+"']"; List<Element> list=dom.selectNodes(xpath); List<ImageModel> imgList=new ArrayList<ImageModel>(); for(Element e:list){ String id=e.attributeValue("id"); imgList.add(getSingleImage("//file[@id='"+id+"']")); } return imgList; } public static List<ImageModel> getAllImages(){ List<Element> list=dom.getRootElement().elements(); List<ImageModel> imgList=new ArrayList<ImageModel>(); for(Element e:list){ String id=e.attributeValue("id"); imgList.add(getSingleImage("//file[@id='"+id+"']")); } return imgList; } }
值对象:
public class ImageModel { private String id; private String userName; private String fileUploadTime; private String fileName; private String newFileName; private String filepath; private String fileMsg; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileUploadTime() { return fileUploadTime; } public void setFileUploadTime(String fileUploadTime) { this.fileUploadTime = fileUploadTime; } public String getNewFileName() { return newFileName; } public void setNewFileName(String newFileName) { this.newFileName = newFileName; } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public String getFileMsg() { return fileMsg; } public void setFileMsg(String fileMsg) { this.fileMsg = fileMsg; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ImageModel other = (ImageModel) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "ImageModel [id=" + id + ", userName=" + userName + ", fileUploadTime=" + fileUploadTime + ", fileName=" + fileName + ", newFileName=" + newFileName + ", filepath=" + filepath + ", fileMsg=" + fileMsg + "]"; } }
map解析成值对象的beanutil
public class BeanUtil { public static<T> T getInstance(Class<T> cls,Map<String, ?> map){ T obj=null; try { obj=cls.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } Field[] fields=cls.getDeclaredFields(); for(Field field:fields){ String fieldName=field.getName(); Object fieldValue=map.get(fieldName); if(fieldValue==null) continue; String fieldNameUp=fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1); try { Method method=cls.getMethod("set"+fieldNameUp, field.getType()); //invoke的第二参数必须是数组 method.invoke(obj, getList(fieldValue)); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return obj; } private static Object[] getList(Object fieldValue){ Object[] list=null; if(fieldValue instanceof Object[]){ Object[] array=(Object[])fieldValue; if(array.length==1) list=array; else if(array.length>1){ list=new Object[1]; list[0]=fieldValue; } } else{ list=new Object[1]; list[0]=fieldValue; } return list; } }
相关文章推荐
- 基于jQuery实现多标签页切换的效果(web前端开发)
- 省市二级联动小案例讲解
- JavaScript学习小结之使用canvas画“哆啦A梦”时钟
- JavaScript提高网站性能优化的建议(二)
- JavaScript关于提高网站性能的几点建议(一)
- JS中的==运算: [''] == false ―>true
- 深入理解javascript作用域第二篇之词法作用域和动态作用域
- javascript中sort排序实例详解
- JavaScript表单焦点自动切换代码
- JavaScript禁止用户多次提交的两种方法
- 内容运营|公众号没话题可写?试试UGC吧~
- 周鸿祎上直播看点很多:美女、音乐、AI、豪宅,可网民最新奇的是他家门口的自动塑封鞋套
- 读懂 Android 中的代码混淆
- C++ 实现银行排队服务模拟
- ES6新特性:JavaScript中Set和WeakSet类型的数据结构
- 【codeforces】Vacations
- Android自定义view详解
- 码神学习(对象)
- 旧瓶装新酒的 Java 8 StringJoiner
- Shell脚本编程总结及速查手册