时间:2021-05-19
功能文件的上传,下载和管理
技术:1.用xml当做数据库存储信息(dom4j,xpath)
2.Java表单的文件上传和下载
3.文件目录的打散 ( Hash目录是一种优化文件存储性能的方法)
需要的jar包:
commons-fileupload-1.2.2.jar、commons-io-2.1.jar、dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar
--------------------------------------------------------------------------------
先写index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>相册管理系统</title> </head> <body> <h1>我的小相册</h1> <a href="jsps/upload.jsp">上传相册</a> <a href="servlets/ShowServlet">浏览相册</a> </body></html>upload.jsp是下载页面放在jsps目录下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> </head> <body> <h1>相处上传</h1> <form action="<%=request.getContextPath()%>/servlets/UploadServlet" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file1"/><br/> 说明:<input type="text" name="desc" /><br/> <input type="submit" value="上传" /> </form> </body></html>photos.xml放在src目录下
<?xml version="1.0" encoding="UTF-8"?><photos></photos>在写值对象PhotoModel
package cn.hncu.demain;public class PhotoModel { private String id; private String realName; private String ext; private String dir; private String dateTime; private String ip; private String desc; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getExt() { return ext; } public void setExt(String ext) { this.ext = ext; } public String getDir() { return dir; } public void setDir(String dir) { this.dir = dir; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "PhotoModel [id=" + id + ", realName=" + realName + ", ext=" + ext + ", dir=" + dir + ", dateTime=" + dateTime + ", ip=" + ip + ", desc=" + desc + "]"; }}写工具类两个:
MyUtil(日期格式化,目录打散代码,随机id代码)
Dom4jFactory(dom4j的相关操作,获取document对象,保存操作)
package cn.hncu.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.UnsupportedEncodingException;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;public class Dom4jFactory { private static Document dom = null; private static String path; static { try { SAXReader sax = new SAXReader(); // 学习一下服务器下的资源路径加载方式(因为我们的资源已经从MyEclipse中发布到Tomcat服务器中了,所以跟原来纯Java项目不一样了) // 利用当前类找到它的类加载器,然后通过该类加载器再去获得资源路径 path = Dom4jFactory.class.getClassLoader().getResource("photos.xml") .getPath(); dom = sax.read(new FileInputStream(path)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public static Document getDom(){ return dom; } public static boolean save(){ try { OutputFormat format=new OutputFormat(); format.setEncoding("utf-8"); XMLWriter w = new XMLWriter( new FileOutputStream(new File(path)),format); w.write(dom); w.close(); return true; } catch (Exception e) { return false; } }}从底层写PhotoDao
package cn.hncu.dao;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.Element;import cn.hncu.demain.PhotoModel;import cn.hncu.utils.Dom4jFactory;public class PhotoDao { //添加 public boolean add(PhotoModel photo){ Document dom=Dom4jFactory.getDom(); Element root=dom.getRootElement(); Element ePhoto=root.addElement("photo"); ePhoto.addAttribute("id", photo.getId()); ePhoto.addAttribute("realName", photo.getRealName()); ePhoto.addAttribute("dir", photo.getDir()); ePhoto.addAttribute("ip", photo.getIp()); ePhoto.addAttribute("dateTime", photo.getDateTime()); ePhoto.addAttribute("ext", photo.getExt()); ePhoto.addElement("desc").setText(photo.getDesc()); boolean boo=Dom4jFactory.save(); return boo; } //浏览 public List<PhotoModel> getAll(){ Document dom=Dom4jFactory.getDom(); List<PhotoModel> list=new ArrayList<PhotoModel>(); Element root=dom.getRootElement(); Iterator<Element> it=root.elementIterator(); while(it.hasNext()){ PhotoModel photo=new PhotoModel(); Element e=it.next(); photo.setId(e.attributeValue("id")); photo.setDateTime(e.attributeValue("dateTime")); photo.setDir(e.attributeValue("dir")); photo.setExt(e.attributeValue("ext")); photo.setIp(e.attributeValue("ip")); photo.setRealName(e.attributeValue("realName")); photo.setDesc(e.elementText("desc")); list.add(photo); } return list; } public PhotoModel getSingleById(String id) { Document dom=Dom4jFactory.getDom(); List<PhotoModel> list=getAll(); for(PhotoModel photo:list){ if(photo.getId().equals(id)){ return photo; } } return null; } public boolean del(String id) { Document dom=Dom4jFactory.getDom(); Element e=(Element) dom.selectSingleNode("//photo[@id='"+id.trim()+"']"); return e.getParent().remove(e); }}最后写四个servlet
UploadServlet 上传Servlet代码
ShowServlet 浏览相册的Servlet端
package cn.hncu.servlets;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class ShowServlet extends HttpServlet { IOException if an error occurred public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); String table="<table border='1' width='100%'>"+ "<tr><th>文件名</th><th>上传ip</th><th>上传时间</th><th>图片</th><th>说明</th><th>操作</th></tr>" ; out.print(table); PhotoDao dao=new PhotoDao(); List<PhotoModel> list=dao.getAll(); for(PhotoModel p:list){ out.print("<tr>"); out.println("<td>"+p.getRealName()+"</td>"); out.println("<td>"+p.getIp()+"</td>"); out.println("<td>"+p.getDateTime()+"</td>"); //输出图片 String path=request.getContextPath()+"/photos/"+p.getDir()+"/"+p.getId()+p.getExt(); out.println("<td><a href='"+path+"'><img src='"+path+"' width='200' height='200'></img></a></td>"); String op="<a href='"+request.getContextPath()+"/servlets/DelServlet?id="+p.getId()+"'>删除</a> "; out.println("<td>"+p.getDesc()+"</td>"); op+="<a href='"+request.getContextPath()+"/servlets/DownServlet?id="+p.getId()+"'>下载</a>"; out.println("<td>"+op+"</td>"); out.print("</tr>"); } out.println("</table>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}DownServlet 下载的服务器代码
package cn.hncu.servlets;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class DownServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id=request.getParameter("id"); response.setContentType("application/force-download"); PhotoModel p=new PhotoDao().getSingleById(id); if(p!=null){ String realName=p.getRealName(); realName=new String(realName.getBytes("iso8859-1"),"utf-8"); response.setHeader("content-Disposition", "attachment;filename=\""+realName+"\""); String relpath=getServletContext().getRealPath("/photos/"+p.getDir()+"/"+p.getId()+p.getExt()); InputStream in=new FileInputStream(relpath); OutputStream out=response.getOutputStream(); System.out.println(relpath); byte buf[]=new byte[1024]; int len=0; while ((len=in.read(buf))!=-1){ out.write(buf,0,len); } out.close(); }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("该文件已经被删除!"); } }}Delservlet 删除操作的服务器
package cn.hncu.servlets;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.hncu.dao.PhotoDao;import cn.hncu.demain.PhotoModel;public class DelServlet extends HttpServlet { 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"); response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); String id=request.getParameter("id"); PhotoModel p=new PhotoDao().getSingleById(id); if(p!=null){ if(!p.getIp().equals(request.getRemoteAddr())){ out.println("你无权进行删除!"); return; } //※※※※以下部分课后补敲的!!!! //1删除数据库中的信息 PhotoDao dao=new PhotoDao(); boolean boo=dao.del(id); //2把服务器硬盘中的文件删除 if(boo){ String fileName="photos/"+p.getDir()+"/"+p.getId()+p.getExt(); String pathFileName = getServletContext().getRealPath(fileName); File f=new File(pathFileName); if(f.exists()){ f.delete(); } String strPath = request.getContextPath()+"/servlets/ShowServlet"; out.println("相片删除成功!<a href='"+strPath+"'>浏览相册</a>"); }else{ out.println("相片删除失败!"); } }else{ response.setContentType("text/html;charset=utf-8"); response.getWriter().println("该文件不存在!"); } }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
数据库管理系统是可以创建维护数据库的,数据库是按照数据结构来组织、存储和管理数据的建立在计算机存储设备上的仓库。 数据库管理系统(英语:DatabaseMan
数据库管理系统的主要功能有:数据定义、数据操作、数据库的运行管理、数据组织存储与管理、数据库的保护及维护、以及通信功能。 数据库管理系统(英语:Databas
数据库系统与文件系统的主要区别如下: 1、数据库系统主要管理数据库的存储、事务以及对数据库的操作。文件系统是操作系统管理文件和存储空间的子系统,主要是分配文件
Android系统有五种数据存储形式,分别是文件存储、SP存储、数据库存储、contentprovider内容提供者、网络存储。其中,前四个是本地存储。存储的类
本文实例讲述了Yii框架session数据库存储操作方法。分享给大家供大家参考,具体如下:在组件中声明session组件开启数据库库存储['components