JavaバージョンのSimple Cloudアルバムを作成すると、実装された関数は次のとおりです。
ユーザーは、一度に1つと複数のファイルをアップロードできます。
ユーザーは、他の人がアップロードした写真をダウンロードできます。
ユーザーは他のすべての人の写真を見ることができます。
ユーザーは、自分のIPを介してアップロードされた写真のみを削除できます。
使用されるテクニック:
ファイルアップロードとダウンロード、デザインモード、DOM4J、XPathなど。
次の2ページを見てみましょう。
ソースコード:
web.xml:
<?xml version = "1.0" encoding = "utf-8"?> <web-appバージョン= "3.0" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instcance" xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name> </display-name> <サーブレットクラス> cn.hncu.servlets.uploadservlet </servlet-class> </servlet> <servlet> <servlet-name> cloudphotoservlet </servlet-name> <servlet-class> <サーブレットクラス> cn.hhncu.servlets.downservlet </servlet-class> </servlet> <servlet> <servlet-name> delservlet </servlet-name> <servlet-class> cn.hhncu.servlets.delservlet </servlet-class> </servlet-mapting> <servlet-mapplet> <url-pattern>/upload </url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> cloudphotoservlet </servlet-name> <url-pattern>/url-pattern> </servet-mapping> <servlet-mapping> <サーブレットマッピング> <サーブレットマッピング> <url-pattern>/servlet/downservlet </url-pattern> </servlet-mapping> <servlet-name> delservlet </servlet-name> <url-pattern>/servlet/delservlet </url-pattern> </servlet-mapping> <welcome-file> jsp </welcome-file> jsp </welcome-file> </welcome-file-list> </web-app>
index.jsp:
<%@ページ言語= "java" import = "java.util。*" pageencoding = "utf-8"%> <!doctype html public " - // w3c // dtd html 4.01 transitional // en"> <html> <head> <title> chxクラウドアルバム> <スクリプト> input.parentelement.parentelement.parentelement; // table.nodename tbody table.removechild(input.parentelement.parentelement); } var t = 1; function addfile(input){tr = input.parentelement.parentelement; //alert(tr.nodename); var str = "<td> select file:</td>"+ "<td> <input type = 'file' name 'name"+ t+ "'> </td>"+ "<td>ファイル説明:</td>"+ "<td> <入力タイプ= 'テキスト' name = 'text"+ t+ "'> </td> onclick = 'delfile(this)'> </td> "; tr.insertadjacenthtml( "beforebegin"、str); } function move(){window.location.href = "/myphoto/cloudphoto"; } </script> <style type = "text/css"> #font {color:red; } </style> </head> <body> <h1> <font id = "font">アルバムアップロード:</font> </h1> <form action = "/myphoto/upload" method = "post" enctype = "multipart/form-data"> <table> <table> <tr> <td> select = "> td </td <td <td <td </td </td </td <"> "ファイル<td>ファイルの説明:</td> <td> <入力タイプ= "text" name = "text1"> </td> <td> <input type = "button" value = "delete file" onclick = "delfile(this)"> </td> </tr> <tr> <td colspan = 2> <入力= "" valy "> <td <td> <td <td> <td> <td> <td> type = "button" value = "add file" onclick = "addfile(this)"> </td> </tr> </table> </form> <form action = "/myphoto/cloudphoto" method = "post" enctype = "multipart/form-data"> <table> <table> <tr> <td colspan = 5> <入力タイプ= onclick = "move()"> </td> </tr> </table> </form> </body> </html>photo.xml:
<?xml version = "1.0" encoding = "utf-8"?> <photos> </photos>
myutils.java:
package cn.hncu.utils;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;public class MyUtils { /** * @return Get UUID */ public static String getUUID(){ return UUID.randomUUID().toString().replace("-", ""); } / ** * @param uuid * @return uuidを介して壊れたパスを取得 * / public static string getdir(string uuid){string dir1 = integer.tohexstring(uuid.hashcode()&0xf); string dir2 = integer.tohexstring((uuid.hashcode()&0xf0)>> 4); return "/"+dir1+"/"+dir2; } //日付時間形式プライベートStatic Static SimpledateFormat SDF = new SimpledateFormat( "yyyyy year mm mont dd Date hh:mm:ss"); / *** @returnアップロード時に日付と時刻を返します*/ public static string getCurrentDateTime(){return sdf.format(new date()); }}dom4jfactory.java:
パッケージcn.hncu.utils; Import java.io.fileinputStream; Import java.io.filenotfoundexception; Import java.io.fileoutputStream; Import java.io.ioexception; Import java.io.io.unsuportedencodingception; org.dom4j.element; import org.dom4j.node; Import org.dom4j.io.saxreader; Import org.dom4j.io.xmlwriter; public class dom4jfactory {private static document dom = null;プライベート静的文字列パス。 //静的ブロック!一度だけ実行されます!機能は、クラスがロードされると、static {try {saxreader sax = new Saxreader()が実行されることです。 //当社のリソースはMyElipseからTomcatサーバーに公開されているため、元のPure Javaプロジェクトとは異なります。 //現在のクラスを使用してクラスローダーを見つけ、クラスローダーを通るリソースパスを取得します。 path = dom4jfactory.class.getClassLoader()。getResource( "photo.xml")。getPath(); // getClassLoader()返品:このオブジェクトで表されるクラスまたはインターフェイスのクラスローダーのロードリソースが見つからない場合、または発信者がリソースを取得するのに十分な許可がない場合は、NULLを返します。 //このメソッドは、最初にリソースの親クラスローダーを検索します。親クラスローダーがnullの場合、検索パスは仮想マシンの内蔵クラスローダーのパスです。 // public string getPath()このURLのパス部分を取得します。 system.out.println(path); dom = sax.read(new FileInputStream(PATH)); } catch(filenotfoundexception e){new new runtimeexception(e); } catch(documentexception e){new new runtimeException(e); }} / ** * @returnアルバムのドキュメントを取得 * / public static document getDocument(){return dom; } / ** * photo.xmlを保存し、ローカルに保存 * / public static boolean save(){try {xmlwriter w = new xmlwriter(new fileoutputStream(path)); w.write(dom); w.close(); trueを返します。 } catch(unsupportedencodingexception e){return false; } catch(filenotfoundexception e){return false; } catch(ioException e){false; }} public static boolean del(string uuid){node node = dom.selectsinglenode( "[@uuid = '"+uuid+"']"); if(node == null){return false; } node.getParent()。remove(node); trueを返します。 } / *** test* @param args* / public static void main(string [] args){system.out.println(getDocument()); }}Photomodel.java-値オブジェクト
パッケージcn.hncu.domain;/***値オブジェクトcapsulation* @author chen haoxiang* 2016-7-24*/public class photomodel {private string uuid; // uuid private string realname = ""; //画像の実際のファイル名(アップロード時のファイル名)プライベート文字列ext;ファイルプライベート文字列IPのアップロード; //アップローダーのIPプライベート文字列DESC; //ファイル説明public String getUuid(){return uuid; } public void setuuid(string uuid){this.uuid = uuid; } 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 [uuid =" + uuid + "、realname =" + realname + "、ext =" + ext + "、dir =" + dir + "、datetime =" + datetime + "、ip =" + ip + "、desc +" }}Photodao.java:
パッケージcn.hncu.photodao.dao; Import java.util.list; import cn.hncu.domain.photomodel; public interface photodao { / *** @param photo* @return save* / public boolean save(photomodel photo); / *** @returnすべての画像情報を返します*/ public List <Photomodel> getAll(); / *** @param uuid* @return uuidを介してカプセル化された値オブジェクトを見つけます*/ public photomodel getsinglebyuid(string uuid); / ** * @param uuid * @return photos.xmlを介して画像の情報を削除 */ public boolean deletexml(string uuid); / ** * @param dir * @returnパスを介してサーバーディスク内の画像の情報を削除 */ public boolean deletefile(String PathFileName);}Photoserimpl.java:
パッケージcn.hncu.photodao.impl; import java.io.file; Import java.util.arraylist; Import java.util.iterator; Import java.util.list; Import org.dom4j.document; document; import org.dom4j.element; Import org.dom.dom.node; cn.hncu.photodao.dao.photodao; Import cn.hncu.utils.dom4jfactory; public class photoseRimplを実装したphotodao {@Override public boolean save(photomodel photion(photomodel photion){document dom = dom4jfactory.getDocument;要素root = dom.getRootelement(); //属性要素P = root.AddElement( "写真")を追加する; p.addattribute( "uuid"、photo.getuid()); p.addattribute( "realname"、photo.getRealName()); p.addattribute( "datetime"、photo.getDateTime()); p.addattribute( "ip"、photo.getip()); p.addattribute( "ext"、photo.getext()); p.addattribute( "dir"、photo.getdir()); p.addattribute( "desc"、photo.getDesc()); dom4jfactory.save()を返します。 } @Override public List <Photomodel> getAll(){list <Photomodel> list = new ArrayList <Photomodel>();ドキュメントdom = dom4jfactory.getDocument();要素root = dom.getRootelement(); iterator <lement> it = root.Elementiterator( "写真"); // dom4jを介してフォト要素のiteratorを取得すると、xpathを使用してすべての写真を見つけることができます// list <node> lists = dom.selectnodes( "// photo [@uuid]"); // iterator <node> it = lists.iterator(); while(it.hasnext()){element e = it.next(); Photomodel Photo = new Photomodel(); photo.setuid(e.attributevalue( "uuid")); photo.setRealName(e.AttributeValue( "RealName")); photo.setDateTime(E.AttributeValue( "DateTime")); photo.setext(e.attributevalue( "ext")); photo.setip(e.attributevalue( "ip")); photo.setdir(e.attributevalue( "dir")); photo.setDesc(e.attributevalue( "desc")); list.add(写真); }返品リスト。 } @Override public Photomodel getSinglebyuid(string uuid){list <photomodel> photos = getall(); for(photomodel photo:photos){if(photo.getuuid()。equals(uuid)){return photo; }} nullを返します。 } @Override public boolean deletexml(string uuid){document dom = dom4jfactory.getDocument();要素e =(要素)dom.selectsinglenode( "// photo [@uuid = '"+uuid.trim()+"']"); return e.getParent()。remove(e); } @Override public boolean deletefile(string pathfilename){try {file file = new file(pathfilename); if(file.exists()){file.delete(); } trueを返します。 } catch(例外e){falseを返します。 }}}photodaofactory.java:
パッケージcn.hncu.photodao.factory; import cn.hncu.photodao.impl.photoserimpl;/*** Factory Method* @author chen haoxiang* 2016-7-24*/public class photodaofactory {public static photoserimpl getphotao() }}uploadservlet.java:
パッケージcn.hncu.servlets; Import java.io.file; import java.io.io.ioexception; Import java.io.printwriter; Import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; inmavax.servletet.htpsert.httpsert.httpsert.httpservlet javax.servlet.http.httpservletresponse; Import org.apache.commons.fileupload.fileitem; Import org.apache.commons.fileupload.fileuploadexception; Import org.apache.commons.fileupload.disk.disk.disk.disk.fileupload; org.apache.commons.fileupload.servlet.servletfileupload; Import cn.hncu.domain.photomodel; Import cn.hncu.photodao.dao.photodao; 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"); Response.getWriter()。print( "<h1>申し訳ありませんが、このページはアクセスの取得!!! </h1>"); Response.getWriter()。print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>"); } public void dopost(httpservletrequest request、httpservletResponse応答)throws servletexception、ioexception {respons.setContentType( "text/html; charset = utf-8");最終的なprintwriter out = response.getWriter(); // anti-black-non-multipart form submission //アップロードツールブールブー= servletfileupload.ismultipartcontent(request); if(!boo){out.print( "<h1>は、通常のフォームの提出方法をサポートしていません!</h1>");戻る; } file file = new file( "d:/photocache"); if(!file.exists()){file.mkdir(); } diskFileItemFactory fifactory = new DiskFileItemFactory(1024*10、file); servletfileupload upload = new servletfileupload(fifactory); upload.setheaderencoding( "utf-8"); //ファイル名を設定する文字列パス= getServletContext()。getRealPath( "/photos"); fileitem fi = null; try {list <fileitem> list = upload.parserequest(request); Photomodel Photo = new Photomodel(); //データカプセル化--- 7プロパティが必要ですphoto.setrealname( ""); int cont = 0; for(fileItem f:list){if(cont!= 0 && cont%2 == 0 &&!photo.getRealName()。equals( "")){photo = new Photomodel(); // re-data capsulation} fi = f; if(fi.isformfield()){//通常のフォームコンポーネント//ファイル説明文字列desc = fi.getString( "utf-8"); photo.setDesc(desc); //#1} else {// anti-black 3-ファイルがファイルコンポーネントで選択されていない場合、(fi.getsize()== 0){photo.setrealname( ""); cont ++;続く; }文字列filename = fi.getName(); filename = filename.substring(filename.lastindexof( "//")+1); // real file name photo.setrealname(filename); //#2 string ext = filename.substring(filename.lastindexof( "。"); // extendextext(ext); //#3 photo.setDateTime(myutils.getCurrentDateTime()); //#4 Photo.setip(request.getRemoteaddr()); //#5 String uuid = myutils.getUuid(); photo.setUuid(uuid); //#6 photo.setdir(myutils.getdir(uuid)); //#7 //ディレクトリファイルdfile = newファイル(path+photo.getdir())を破壊します。 if(!dfile.exists()){dfile.mkdir(); } fi.write(new file(path+photo.getdir()+"/"+photo.getuuid()+photo.getext())); } cont ++; if(cont%2 == 0 &&!photo.getRealName()。equals( "")){photodao dao = photodaofactory.getphotodao(); boo = dao.save(写真); //ディスクに保存 - 方法2:fileutils.copyinputstreamtofile(in、new file(filename2)); //※2※イメージファイルをサーバーハードディスク写真= new Photomodel(); // remencapsulation}}} catch(fileuploadexception e){e.printstacktrace(); } catch(Exception e){e.printstacktrace(); }最後に{if(fi!= null){fi.delete(); } if(dom4jfactory.save()){out.print( "<h1> uploaded uploaded upload!</h1>"); out.print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>"); } else {out.print( "<h1> upload failed!</h1>"); out.print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>"); }}}}すべてのファイルを表示-Cloudphotoservlet.javaを表示します
パッケージ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.hncu.domain.photomodel;インポートcn.hhncu.dao.photodao;インポートcn.hncu.photodao.factory.photodaofactory doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception {string pwd =(string)request.getParameter( "pwd"); if( "chx" .equals(pwd)){dopost(request、response); } else {respons.setContentType( "text/html; charset = utf-8"); Response.getWriter()。print( "<h1>申し訳ありませんが、アクセスする許可がありません!!! </h1>"); }} public void dopost(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {respons.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> chxクラウドアルバム</title> </head>"); out.println( "<body>"); out.println( "<table border = '1px; double;#ff0000'>"); out.println( "<tr>"); out.println( "<tr>"); out.println( "<td> file name </td>"); out.println( "<td>アップロード時間"); out.println( "<td> file </td>"); out.println( "<td>ファイル説明</td>"); out.println( "<td>操作</td>"); out.println( "</tr>"); string tdwh = "style = 'width:200px; height:200px;'"; //すべての写真を表示しますphotodao dao = photodaofactory.getphotodao();リスト<Photomodel>写真= dao.getall(); for(photomodel photo:photos){string filename = photo.getRealName(); string time = photo.getDateTime(); //出力画像文字列= request.getContextPath() + "/photos/" + photo.getDir() + "/" + photo.getUuid() + photo.getext(); // system.out.println(path); // /myphoto/photos//7/c/a1237a48a6aa451cb222fa78b15bafcea.jpg string img = "<a href = '" + "'> <img src = '" + path + "'/> </a>";文字列desc = photo.getDesc(); string delstr = "<a href = '/myphoto/servlet/delservlet?uuid =" + photo.getuid() + "'> delete </a>"; string downstr = "<a href = '/myphoto/servlet/downservlet?uuid =" + photo.getuid() + "'> download </a>"; out.println( "<td" + tdwh + ">" + filename + "</td>"); out.println( "<td" + tdwh + ">" + time + "</td>"); out.println( "<td" + tdwh + ">" + img + "</td>"); out.println( "<td" + tdwh + ">" + desc + "</td>"); out.println( "<td" + tdwh + ">" + delstr + "" + downstr + "</td>"); out.println( "</tr>"); } out.println( "<tr>"); out.println( "</tr>"); out.println( "</table>"); out.println( "</body>"); out.println( "</html>"); out.flush(); out.close(); }}ファイルを削除-Delservlet.java
パッケージcn.hncu.servlets; Import java.io.ioexception; import java.io.printwriter; Import javax.servlet.servletexception; Import javax.servlet.http.httpservlet; Import javax.servlet.http.httpservletrequest; import; javax.servlet.http.httpservletresponse;インポートcn.hncu.domain.photomodel;インポートcn.hhncu.dao.photodao;インポートcn.hncu.photodao.factory.photodaofactory photodaofactory.getphotodao(); public void doget(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {string uuid = request.getparameter( "uuid");文字列ip = request.getRemoteaddr(); Response.setContentType( "text/html; charset = utf-8"); printwriter out = response.getWriter(); Photomodel Photo = dao.getsinglebyuuid(uuid); if(photo!= null){if(!photo.getip()。equals(ip)){out.print( "<h1>このファイルを削除する許可がありません!!!!!!</h1>"); out.print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>");戻る ; } // 1。データベースで情報を削除しますboolean boo = dao.deletexml(uuid); if(boo){string filename = "photos/"+photo.getdir()+"/"+photo.getuuid()+photo.getext(); string pathfilename = getservletcontext()。getRealPath(filename); if(dao.deletefile(pathfilename)){//アルバムページResponse.sendredirect( "/myphoto/cloudphoto?pwd = chx"); } else {out.print( "<h1>はサーバーから削除できません。ファイルは占有されています!!! </h1>"); out.print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>"); }} else {out.print( "<h1>ファイルは存在しなくなりました!!! </h1>"); out.print( "<a href = 'javascript:history.go(-1)'>前のページに戻る</a>"); }}}}ファイル-DownServlet.javaをダウンロードします
パッケージcn.hncu.servlets; import java.io.fileinputStream; Import java.io.ioexception; Import java.io.inputStream; Import java.outputStream; Import java.net.urlencoder; Import javax.servletexception; javax.servletletetlet.htptelet; javax.servlet.http.httpservletrequest; Import javax.servlet.http.httpservletresponse; Import cn.hncu.domain.photomodel;インポートダウンサーブレットはhttpservletを拡張します{private photodao dao = photodaofactory.getphotodao(); public void doget(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {dopost(request、response); } public void dopost(httpservletrequest request、httpservletResponse応答)servletexception、ioexception {string uuid = request.getparameter( "uuid"); System.out.println(uuid); Photomodel Photo = dao.getsinglebyuuid(uuid); System.out.println(写真); if(photo!= null){//応答ヘッダーを設定します - コンテンツレシーバー - ブラウザがこの応答ヘッダーを表示すると、それは//であると思われるダウンロードプログラムを開きます(サンダーが認識された場合、サンダーは自動的に開きます、「ダイアログボックスが開きます」。 string realname = photo.getRealName(); string agent = request.getheader( "user-agent"); System.out.println(Agent); if(agent.indexof( "mozilla")!= -1){// firefox browser response.setheader( "content-disposition"、 "attachment; fileName ="+ new String(realname.getBytes( "gb2312")、 "ISO-8859-1")); } else {//文字化けされた中国語の問題を解決します(次の文を使用してファイル名をエンコードします)realname = urlencoder.encode(realname、 "utf-8"); Response.setheader( "content-disposition"、 "attachment; filename =/" "+realname+"/""); //注:「cttachment;」欠落していない場合、ブラウザは新しいウィンドウで直接開きます}文字列filename = "photos/"+photo.getdir()+"/"+photo.getuuid()+photo.getext(); string pathfilename = getservletcontext()。getRealPath(filename); inputStream in = new fileInputStream(pathFileName); outputStream out = response.getOutputStream();バイトbuf [] = new byte [2048]; int len = 0; while((len = in.read(buf))!= -1){out.write(buf、0、len); } out.close(); in.close(); } else {respons.setContentType( "text/html; charset = utf-8"); Response.getWriter()。println( "<h1>このファイルは削除されました</h1>"); }}}デモンストレーションの結果
私はこれを実証しません、その前に写真があり、すべてのソースコードを与えました。興味があれば、自分でいくつかの改善をすることができます。
実際、これは他のタイプのファイルをアップロードすることもできます。これは、保護サフィックス名がなく、文字ストリーミングを使用して送信するため、歪んでいないためです(クラウドディスクとして処理できます~~)! !
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。