機能ファイルのアップロード、ダウンロード、および管理テクノロジー:1。XMLをデータベースストレージ情報(DOM4J、XPath)として使用します
2。Javaフォームのアップロードとダウンロード
3.ファイルディレクトリの分解(ハッシュディレクトリは、ファイルストレージパフォーマンスを最適化する方法です)
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を書き込みます
<%@ページ言語= "java" import = "java.util。*" pageencoding = "utf-8"%> <!doctype html public " - // w3c // dtd html 4.01 transitional // en"> <html> <head> <タイトル>アルバム管理システム</head> < href = "jsps/upload.jsp">アップロードアルバム</a> <a href = "servlets/showervlet"> browse bulbum </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> Action = "<%= request.getContextPath()%>/servlets/uploadservlet" Method = "post" enctype = "multipart/form-data"> file:<input = "file" name = "file1"/> <br/>説明:<入力タイプ= "テキストname =" desc "/> <input =" "vall"/> < </body> </html>
SRCディレクトリにphotos.xmlを入れます
<?xml version = "1.0" encoding = "utf-8"?> <photos> </photos>
値オブジェクトフォトモデルを書き込みます
パッケージcn.hncu.demain; public class photomodel {private string id;プライベート文字列RealName;プライベート文字列ext;プライベート文字列dir;プライベート文字列dateTime;プライベート文字列IP;プライベート文字列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 + "]; }}ライティングツールには2つのタイプがあります。
myutil(日付のフォーマット、ディレクトリブレイクコード、ランダムIDコード)
パッケージcn.hncu.utils;インポートjava.text.simpledateformat; import java.util.date; import java.util.uuid; public class myutils {} private static simpledateformat format = new simpledateformat( " public static string getCurrentDateTime(){return format.format(new date()); } public static string getuuid(){uuid uuid = uuid.randomuid(); string id = uuid.toString()。factereall( " - "、 ""); IDを返します。 } public static string getDir(String UUID){String dir1 = integer.tohexstring(uuid.hashcode()&0xf); string dir2 = integer.tohexstring((uuid.hashcode()&0xf0)>> 4); dir1+"/"+dir2を返します。 }}DOM4JFactory(DOM4Jの関連操作、ドキュメントオブジェクトを取得し、操作を保存)
パッケージcn.hncu.utils; Import java.io.file; Import java.io.fileinputStream; Import java.io.fileenotfoundexception; Import java.fileoutputStream; Import java.io.io.unsuptedencodingexception; Import org.document; Dom.document.documentのインポートorg.dom4j.io.outputformat; Import org.dom4j.io.saxreader; Import org.dom4j.io.xmlwriter; public class dom4jfactory {private static document dom = null;プライベート静的文字列パス。 static {try {saxreader sax = new Saxreader(); //サーバーの下にリソースパスをロードする方法を学ぶ(当社のリソースがMyeclipseからTomcatサーバーに公開されているため、元のPure Javaプロジェクトとは異なるため) 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(); trueを返します。 } catch(例外e){falseを返します。 }}}最下層からPhotodaoを書きます
パッケージ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.cu.utls.dom4jftautory cncu.utls.dom4jftomodel; boolean add(photomodel photo){document dom = dom4jfactory.getdom();要素root = dom.getRootelement();要素ephoto = root.addelement( "写真"); 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(); booを返します。 } //パブリックリスト<Photomodel> getall(){document dom = dom4jfactory.getdom();リスト<Photomodel> list = new ArrayList <Photomodel>();要素root = dom.getRootelement(); iterator <lement> it = root.Elementiterator(); while(it.hasnext()){photomodel photo = new Photomodel();要素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(写真); }返品リスト。 } public Photomodel getsinglebyid(string id){document dom = dom4jfactory.getdom();リスト<Photomodel> list = getall(); for(photomodel photo:list){if(photo.getid()。equals(id)){return photo; }} nullを返します。 } public boolean del(string id){document dom = dom4jfactory.getdom();要素e =(要素)dom.selectsinglenode( "// photo [@id = '"+id.trim()+"']"); return e.getParent()。remove(e); }}最後に4つのサーブレットを書きます
UploadServletアップロードサーブレットコード
パッケージcn.hncu.servlets; Import java.io.file; import java.io.ioexception; Import java.io.inputstream; Import java.io.io.io.printwriter; Import java.util.list; Import javax.servlet.servletexception; Import javax.http.httpsevlet; javax.servlet.http.httpservletrequest; import javax.servlet.http.httservletresponse; Import org.apache.commons.fileupload.fileitem; Import org.apache.commons.fileupload.fileuploadexception; apache.commons.fileupload.disk.diskfileitemfactory; Import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.fileutils; inart cn.hncu.dao.photodao; photodao; photodao; import cncutodao; cn.hncu.utils.myutils; public class uploadservlet extends httpservlet {public void doget(httpservletrequest request、httpservletresponse応答)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サーブレット</title> </head>"); out.println( "<body>"); out.println( "get uploadはサポートされていません!"); out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); } public void dopost(httpservletrequest request、httpservletResponse応答)throws servletexception、ioexception {respons.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"); //ファイル名のエンコードを設定するために使用します。 fileitem fi = null; try {list <fileitem> list = upload.parserequest(request); Photomodel Photo = new Photomodel(); //データカプセル化--- 7属性が必要です。 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( "no file selected!");戻る; } if(realname.indexof( "//")!= -1){realname = realname.substring(realname.lastindexof( "//")+1); } photo.setRealName(RealName); // REALファイル名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()); Photodao dao = new Photodao(); boo = dao.add(写真); //上記の写真情報が正常に保存された場合、画像ファイルを受信してサーバーハードディスクに保存し始めます(boo){system.out.println(dao); path = path+"/"+photo.getDir();ファイルdir = new file(path); if(!dir.exists()){dir.mkdir(); } string filename = path+"/"+photo.getid()+photo.getext(); fileutils.copyinputstreamtofile(in、new file(filename)); string strpath = request.getContextPath()+"/servlets/shoshervlet"; out.print( "アップロードされました! } else {out.print( "upload failed!"); }} catch(fileuploadexception e){新しいruntimeexception( "upload failed!"); "、e);}最後に{if(fi!= null){fi.delete();}} out.flush(); out.close();}}}ブラウジングアルバムのサーブレット側をshowert
パッケージ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.htp.httptspletletuest; javax.servlet.http.httpservletresponse;インポートcn.hhncu.dao.photodao;インポートcn.hhncu.demain.photomodel;パブリッククラスショーサーバー{httpservlet {ioexceptionが発生した場合は、httpservletreletretreest doestのリクエスト(httpsreletreletretretreterspesterpesterpesterspectons)が発生しました。 ioException {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)throws servletexception、ioexception {respons.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サーブレット</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(テーブル); Photodao dao = new Photodao();リスト<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>"); //出力画像文字列パス= request.getContextPath()+"/photos/"+p.getdir()+"/"+p.getid()+p.getext(); out.println( "<td> <a href = '"+path+"'> <img src = '"+path+"' width = 'height =' 200 '> </img> </a> </td>"); string op = "<a href = '"+request.getContextPath()+"/servlets/delservlet?id ="+p.getid()+"'> delete </a>"; out.println( "<td>"+p.getdesc()+"</td>"); op+= "<a href = '"+request.getContextPath()+"/servlets/downServlet?id ="+p.getid()+"'> download </a>"; out.println( "<td>"+op+"</td>"); out.print( "</tr>"); } out.println( "</table>"); out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); }}DownServletによってダウンロードされたサーバーコード
パッケージcn.hncu.servlets; Import java.io.fileinputStream; Import java.io.fileoutputStream; Import java.io.io.inputStream; Import java.io.outputStream; Import java.outputStream; Import java.io.io.putectceptice; import java.net.net.net.net.net.urlentect. javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; Import javax.servlet.htttpservletresponse; Import cn.hncu.dao.photodao;インポート{public void doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)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);バイトbuf [] = new byte [1024]; int len = 0; while((len = in.read(buf))!= -1){out.write(buf、0、len); } out.close(); } else {respons.setContentType( "text/html; charset = utf-8"); Response.getWriter()。println( "このファイルは削除されました!"); }}}DelServlet Delete Server
パッケージ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; javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; Import javax.servlet.servlet.servlet.httpservletResponse;インポートcn.hncu.dao.photodao;インポート{public void doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {request.setcharacterencoding( "utf-8"); Response.setContentType( "text/html; charset = utf-8"); printwriter out = response.getWriter();文字列id = request.getParameter( "id"); Photomodel P = new Photodao()。getSinglebyid(id); if(p!= null){if(!p.getip()。equals(request.getRemoteaddr())){out.println( "削除する許可がない!");戻る; } //※※※※次の部品が次のクラスに追加されます!!! // 1デレートデータベースの情報Photodao dao = new Photodao(); boolean boo = dao.del(id); // 2deleteサーバーのファイルハードディスクif(boo){string filename = "photos/"+p.getdir()+"/"+p.getid()+p.getext(); string pathfilename = getservletcontext()。getRealPath(filename);ファイルf = new file(pathfilename); if(f.exists()){f.delete(); } string strpath = request.getContextPath()+"/servlets/showervlet"; out.println( "写真削除に正常に!<a href = '"+strpath+"'> browse bualb </a>"); } else {out.println( "photo delete failed!"); }} else {respons.setContentType( "text/html; charset = utf-8"); Response.getWriter()。println( "このファイルは存在しません!"); }}}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。