相册管理系统(Java表单+xml数据库存储)
程序员文章站
2024-03-13 15:03:15
功能文件的上传,下载和管理
技术:1.用xml当做数据库存储信息(dom4j,xpath)
2.java表单的文件上传和下载
3.文件目录的打散 ( hash目...
功能文件的上传,下载和管理
技术: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代码)
package cn.hncu.utils; import java.text.simpledateformat; import java.util.date; import java.util.uuid; public class myutils { private myutils() { } private static simpledateformat format=new simpledateformat("yyyy年mm月dd日 hh:mm:ss"); public static string getcurrentdatetime(){ return format.format(new date()); } public static string getuuid(){ uuid uuid=uuid.randomuuid(); string id=uuid.tostring().replaceall("-", ""); return id; } public static string getdir(string uuid){ string dir1=integer.tohexstring(uuid.hashcode() & 0xf); string dir2=integer.tohexstring((uuid.hashcode() & 0xf0)>>4); return dir1+"/"+dir2; } }
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代码
package cn.hncu.servlets; import java.io.file; import java.io.ioexception; import java.io.inputstream; 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 org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.fileutils; import cn.hncu.dao.photodao; import cn.hncu.demain.photomodel; import cn.hncu.utils.myutils; public class uploadservlet extends httpservlet { public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=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>"); out.println("不支持get方式上传!"); out.println(" </body>"); out.println("</html>"); out.flush(); out.close(); } public void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); printwriter out = response.getwriter(); string path=request.getservletcontext().getrealpath("/photos"); diskfileitemfactory factory=new diskfileitemfactory(); factory.setrepository(new file("g:/a")); servletfileupload upload = new servletfileupload(factory); upload.setsizemax(1024*1024*10);//最大10m upload.setheaderencoding("utf-8");//用于设置文件名的编码,相当于:request.setcharacterencoding("utf-8"); fileitem fi=null; try { list<fileitem> list=upload.parserequest(request); photomodel photo = new photomodel();//数据封装---需要7个属性 boolean boo=false; inputstream in = null; for(fileitem fi2:list){ fi=fi2; if(fi.isformfield()){ string desc=fi.getstring("utf-8"); photo.setdesc(desc);//desc }else{ in=fi.getinputstream(); string realname=fi.getname(); if(realname==null || realname.trim().equals("")){ out.print("没有选择文件!"); return; } if(realname.indexof("\\")!=-1){ realname=realname.substring(realname.lastindexof("\\")+1); } photo.setrealname(realname);//真实文件名 string ext=realname.substring(realname.lastindexof(".")); photo.setext(ext);//3 photo.setdatetime(myutils.getcurrentdatetime());//4 photo.setid(myutils.getuuid());//5 photo.setdir(myutils.getdir(photo.getid()));//6 photo.setip(request.getremoteaddr());//7 } } //把相片信息存储到数据库 photodao dao=new photodao(); boo=dao.add(photo); //如果上面的相片信息保存成功,那么才开始接收图片文件,把它保存到服务器硬盘 if(boo){ system.out.println(dao); path=path+"/"+photo.getdir(); file dir=new file(path); if(!dir.exists()){ dir.mkdirs(); } string filename=path+"/"+photo.getid()+photo.getext(); fileutils.copyinputstreamtofile(in, new file(filename)); string strpath = request.getcontextpath()+"/servlets/showservlet"; out.print("上传成功!<a href='"+strpath+"'>浏览相册</a>"); }else{ out.print("上传失败!"); } } catch (fileuploadexception e) { throw new runtimeexception("上传失败!", e); }finally{ if(fi!=null){ fi.delete(); } } out.flush(); out.close(); } }
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("该文件不存在!"); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。