Escrevendo uma versão java do álbum de nuvem simples, as funções implementadas são:
Os usuários podem fazer upload de um a vários arquivos por vez.
Os usuários podem baixar fotos enviadas por outras pessoas.
Os usuários podem visualizar fotos de todos os outros.
Os usuários podem excluir apenas fotos enviadas por meio de seu próprio IP.
Técnicas usadas:
Enviamento e download de arquivo, modo de design, dom4j, xpath, etc.
Vejamos as próximas duas páginas:
código -fonte:
web.xml:
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>cn.hncu.servlets.UploadServlet</servlet-class> </servlet> <servlet> <servlet-name>cloudPhotoServlet</servlet-name> <servlet-class>cn.hncu.servlets.cloudPhotoServlet</servlet-class> </servlet> <servlet> <servlet-name>DownServlet</servlet-name> <Verlet-class> cn.hncu.servlets.downservlet </servlet-class> </servlet> <sivlet> <Servlet-name> DELSERVLET </Servlet-NAME> </servlet-class> cn.hncu.hncu.servlets.delSletlet </servlet-class> </sererlet> <stlett-mapp-Mapping.NCUPLEG. </url-tattern>/upload </url-tattern> </servlet-mapping> <Verlet-mapping> <Verlet-name> Cloudphotoservlet </servlet-name> <url-pattern>/Cloudphoto </url-tattern> </servlet--Mapping> servlet> <verlet> </url-tattern> <url-pattern>/servlet/downServlet </url-tattern> </servlet-mapping> <Servlet-mapping> <Verlet-name> delservlet </sirtlet-name> <url-tattern>/servlet/delservlet </erl-stattern> </servlet-mapping> <lorde>-file-list> <lide-File> </list-list> </web-App>
index.jsp:
<%@ página linguagem = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! tabela = input.parenteLement.parenteLement.parenteLement; // table.nodename tbody tabela.removechild (input.parenterement.parentelement); } var t = 1; função addfile (input) {tr = input.parentElement.parenteLement; //alert(tr.nodename); var str = "<td> Selecione Arquivo: </td>"+ "<td> <input type = 'file' name = 'file"+ t+ "'> </td>"+ "<td> FILE Descrição: </td>"+ "<td> <td type = 'text =' 't+"' ''> </td> "" OnClick = 'Delfile (this)'> </td> "; tr.Insertadjacenthtml ("Anteriorbegin", STR); } função move () {window.location.href = "/myphoto/Cloudphoto"; } </script> <style type = "text/css"> #font {color: vermelho; } </style> </ad Head> <body> <h1> <font id = "font"> album upload: </font> </h1> <formulário action = "/myphoto/upload" method = "post" rtype = "multipart/form-data"> <tr> <tr> <td> select: file: </td> <tirt> <tirt> <td> <td> <tty) (field> <ttype = "FILT) <T.) <td> File description: </td> <td> <input type="text" name="text1"> </td> <td> <input type="button" value="delete file" onclick="delFile(this)"> </td> </tr> <tr> <td colspan=2> <input type="submit" value="upload file"> </td> <td colspan = 3> <input type = "button" value = "adicionar arquivo" onclick = "addfile (this)"> </td> </tr> </tabela> </form> <form ação = "/myphoto/cloudphoto" method = "post" coltype = "multipart/form-data"> <tat> <tritão "<t> OnClick = "Move ()"> </td> </tr> </tabela> </morm> </body> </html>foto.xml:
<? xml versão = "1.0" coding = "utf-8"?> <hotos> </fotos>
Myutils.java:
pacote cn.hncu.utils; importar java.text.simpledateFormat; importar java.util.date; importar java.util.uuid; public class myutils { / ** * @return obtenha uuid * / public static string getUuid () {return (. } / ** * @param uuid * @return Obtenha o caminho quebrado através de uuid * / public static string getdir (string uuid) {string dir1 = intege.tohexstring (uuid.hashcode () & 0xf); String dir2 = Integer.toHexString ((uuid.hashcode () & 0xf0) >> 4); retornar "/"+dir1+"/"+dir2; } // formato de data-hora private static simpledateFormat sdf = new SimpleDateFormat ("anoaa ano mm mês dd data hh: mm: ss"); / *** @return retorna a data e a hora ao fazer upload*/ public static string getCurrentDateTime () {return sdf.format (new Date ()); }}Dom4jFactory.java:
pacote cn.hncu.utils; importar java.io.fileInputStream; importar java.io.filenotfoundException; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.UnsupportEngOdException; import.dom4j.doment; org.dom4j.Element; importar org.dom4j.node; importar org.dom4j.io.saxReader; importar org.dom4j.io.xmlwriter; public class Dom4jFactory {Private Static Document Dom = null; Caminho de cordas estáticas privadas; // Bloco estático! Só vai correr uma vez! O recurso é que, quando a classe é carregada, estático {try {saxReader sax = new saxReader () é executado; // Como nossos recursos foram publicados do Myelipse para o servidor Tomcat, ele é diferente do projeto Java Pure original. // Use a classe atual para encontrar seu carregador de classe e, em seguida, obtenha o caminho de recursos através do carregador de classe. caminho = dom4jFactory.class.getclassloader (). getResource ("foto.xml"). getPath (); // getClassLoader () Retorna: Carregando o carregador de classe da classe ou interface representada por esse objeto // public URL getResource (nome da string) Retorna: lendo o objeto URL do recurso; Se o recurso não puder ser encontrado ou o chamador não tiver permissão suficiente para obter o recurso, retorne nulo. // Este método primeiro procura o carregador de classe pai do recurso; Se o carregador de classe pai for nulo, o caminho de pesquisa será o caminho do carregador de classe interno da máquina virtual. // public string getPath () recebe a parte do caminho deste URL. System.out.println (caminho); dom = sax.read (new FileInputStream (caminho)); } catch (filenotfoundException e) {tiro novo RUNTimeException (e); } Catch (DocumentException e) {THLHEN RUNTIMEEXCECTION (E); }} / ** * @return Obtenha o documento do álbum * / Public Static Document getDocument () {return dom; } / ** * Salvar foto.xml e salvar no local * / public estático boolean save () {try {xmlWriter w = new XMLWriter (new FileOutputStream (Path)); W.Write (DOM); w.Close (); retornar true; } catch (não suportadoEncodingException e) {return false; } catch (filenotfoundException e) {return false; } catch (ioexception e) {return false; }} public static boolean del (string uuid) {node node = dom.selectSingleNode ("[@uuid = '" "+uuid+"'] "); if (node == null) {return false; } node.getParent (). Remover (nó); retornar true; } / *** teste* @param args* / public static void main (string [] args) {System.out.println (getDocument ()); }}Photomodel.java - objeto de valor
pacote cn.hncu.Domain;/*** Encapsulamento de objeto Valor* @Author Chen Haoxiang* 2016-7-24*/public class Photomodel {private string uuid; // uuid private string realname = ""; // o nome real de string da imagem (nome do arquivo quando upload) private string extr; arquivo private string ip; // o ip private string do uploader Desc; // O arquivo Descrição Public String 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 }}Photodao.java:
pacote cn.hncu.photodao.dao; importar java.util.list; importar cn.hncu.domain.photomodel; interface pública fotodao { / *** @param foto* @return Salvar dados* / public boolean (fotoomodel foto); / *** @return retorna todas as informações da imagem*/ Lista pública <Photomodel> getall (); / *** @param uuid* @return Encontre o objeto de valor encapsulado através do uuid*/ public fotomodel getsingleByuuid (string uuid); / ** * @param uuid * @return Excluir as informações da imagem em fotos.xml através de uuid */ public boolean Deletexml (string uuid); / ** * @param dir * @return Excluir as informações da imagem no disco do servidor através do caminho */ public boolean DeleteFile (String PathFileName);}Pameerimpl.java:
pacote cn.hncu.photodao.impl; importar java.io.file; importar java.util.ArrayList; importar java.util.iterator; importar java.util.list; importin; import.Mom4J.Dom4j.document; import org.domement; cn.hncu.photodao.dao.photodao; importar cn.hncu.utils.dom4jFactory; classe pública PhotoseriMpl implementa Photodao {@Override public boolean salvar (foto do fotomodel) {document Dom = dom4jFactory.getDocument (); Elemento root = dom.getrootelement (); // Adicionar elemento de atributo p = root.addElement ("foto"); p.addattribute ("uuid", foto.getuuid ()); p.addattribute ("realname", foto.getRealName ()); P.Addattribute ("DateTime", Photo.getDateTime ()); p.addattribute ("ip", foto.getip ()); P.Addattribute ("ext", foto.getext ()); p.addattribute ("dir", foto.getDir ()); P.Addattribute ("Desc", foto.getDesc ()); return dom4jfactory.save (); } @Override Public List <Photomodel> getall () {list <Photomodel> list = new ArrayList <Photomodel> (); Documento dom = dom4jFactory.getDocument (); Elemento root = dom.getrootelement (); Iterator <lement> it = root.elementIterator ("foto"); // Obtenha o iterador do elemento fotográfico através do DOM4J, e você também pode encontrar todas as fotos através do XPath // List <Node> lists = dom.selectNodes ("// foto [@uuid]"); // iterator <Node> it = lists.iterator (); while (it.hasnext ()) {elemento e = it.next (); Foto de fotomodelo = novo Photomodel (); foto.setUuid (E.AttributeValue ("uuid")); foto.SetRealName (E.AttributeValue ("Realname")); foto.SetDateTime (E.AttributeValue ("DateTime")); foto.SETEXT (E.AttributeValue ("ext")); foto.setip (e.attributeValue ("ip")); foto.SetDir (E.AttributeValue ("dir")); foto.SetDesc (E.AttributeValue ("Desc")); list.add (foto); } Lista de retorno; } @Override public Photomodel GetsingleByuuid (String uuid) {List <Photomodel> fotos = getall (); para (Foto Photomodel: Fotos) {if (foto.GeTuuid (). Equals (uuid)) {return photo; }} retornar nulo; } @Override public boolean Deletexml (String uuid) {document Dom = dom4jFactory.getDocument (); Elemento e = (elemento) dom.selectSinglenode ("// foto [@uuid = '"+uuid.trim ()+"']"); retornar e.getParent (). Remover (e); } @Override public boolean DeleteFile (String PathFileName) {try {file file = new File (PathFileName); if (file.exists ()) {file.delete (); } retornar true; } catch (Exceção e) {return false; }}}Fotodaofactory.java:
pacote cn.hncu.photodao.factory; importar cn.hncu.photodao.impl.photoserimpl;/*** Método da fábrica* @author chen haoxiang* 2016-7-24*/public class Photodaofactory {public static photerImpl getphotodao; }}UploadServlet.java:
pacote cn.hncu.servlets; importar java.io.file; importar java.io.ioException; importar java.io.printwriter; importar java.util.list; importar javax.servlet.servleTexcept; import javax.servlet.http.htpslettlet; importando; javax.servlet.http.httpServletReQuest; importar javax.servlet.http.httpServletResponse; importar org.apache.commons.fileupload.fileitem; import orgache.commons.fileUplOad.fileUploadex org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import cn.hncu.domain.PhotoModel;import cn.hncu.photoDao.Dao.PhotoDao;import cn.hncu.photoDao.factory.PhotoDaoFactory;import cn.hncu.utils.Dom4jFactory;import cn.hncu.utils.MyUtils;public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Response.setContentType ("Texto/html; charset = utf-8"); Response.getWriter (). Print ("<H1> Desculpe, esta página não suporta obter acesso !!! </h1>"); Response.getWriter (). print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); } public void DoPost (solicitação httpServletRequest, resposta httpSertletResponse) lança servletexception, ioexception {Response.setContentType ("text/html; charset = utf-8"); Final PrintWriter Out = Response.getWriter (); // Anti-Black-Non-Multipart Formulário Submissão // Use a ferramenta de upload boolean boo = servletfileUpload.ismultipartContent (solicitação); if (! boo) {out.print ("<h1> não suporta o método de envio de formulários ordinários! </h1>"); retornar; } Arquivo de arquivo = novo arquivo ("d:/photocache"); if (! file.exists ()) {file.mkdir (); } DiskFileItemFactory fifactory = new DiskFileItemFactory (1024*10, arquivo); ServletfileUpload upload = new ServletFileUpload (Fifactory); upload.setheadeRencoding ("utf-8"); // Defina o nome do arquivo que codifica o caminho da string = getServletContext (). getRealPath ("/fotos"); FileItem fi = null; tente {list <FileItem> list = upload.parserequest (request); Foto de fotomodel = new Photomodel (); // encapsulamento de dados --- 7 Propriedades são necessárias fotos.SetRealName (""); int cont = 0; para (fileItem f: list) {if (cont! = 0 && cont%2 == 0 &&! foto.getRealName (). Equals ("")) {foto = new Photomodel (); // encapsulamento re-data} fi = f; if (fi.isformfield ()) {// componente de formulário normal // obtenha o arquivo Descrição String desc = fi.getString ("utf-8"); foto.setDesc (desc); //#1} else {// anti-black 3-se o arquivo não estiver selecionado no componente do arquivo se (fi.getSize () == 0) {foto.SetRealName (""); cont ++; continuar; } String filename = fi.getName (); FILENAME = FILENAME.SUBSTRING (FILENAME.LASTIndexOf ("//")+1); // Nome do arquivo real Photo.SetRealName (nome do arquivo); //#2 String ext = filename.substring (FILENAME.LASTIndexOF (". foto.SetDateTime (myutils.getCurrentDateTime ()); //#4 foto.setip (request.getRemoTeaddr ()); //#5 string uuid = myutils.getuuid (); foto.SetUuid (uuid); //#6 foto.SetDir (myutils.getdir (uuid)); //#7 // interrompe o arquivo de diretório dfile = novo arquivo (caminho+foto.getDir ()); if (! dfile.exists ()) {dfile.mkdir (); } fi.Write (novo arquivo (caminho+foto.getDir ()+"/"+foto.getuUid ()+foto.getext ())); } cont ++; if (cont%2 == 0 &&! foto.getRealName (). Equals ("")) {photodao dao = fotodaofactory.getphotodao (); boo = dao.save (foto); // Salvar no disco - Método 2: fileUtils.copyInputStreamTofile (in, novo arquivo (FileName2)); // ※ 2 ※ armazenando o arquivo de imagem no disco rígido do servidor Photo = new Photomodel (); // reencapsulation}}} catch (fileUPloadexe e) {e.printstack}; } catch (Exceção e) {e.printStackTrace (); } finalmente {if (fi! = null) {fi.delete (); } if (dom4jFactory.Save ()) {out.print ("<H1> carregado com sucesso! </h1>"); out.print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); } else {out.print ("<h1> upload falhou! </h1>"); out.print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); }}}}Mostre todos os arquivos -cloudphotoServlet.java
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; importar cn.hncu.domain.photomodel; importar cn.hncu.photodao.dao.photodao; importação cn.hncu.photodao.Factory.PhotOofactory; ClassenTenslet PublicOnTeNSLET {PublicOnTenslet HumpSletLend (PublicOnTenslet; Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {string pwd = (string) request.getParameter ("pwd"); if ("chx" .equals (pwd)) {dopost (solicitação, resposta); } else {Response.SetContentType ("text/html; charset = utf-8"); Response.getWriter (). Print ("<H1> Desculpe, você não tem permissão para acessar !!! </h1>"); }} public void DoPost (solicitação httpServletRequest, resposta httpSertLeSponse) lança servletexception, ioexception {Response.setContentType ("text/html; charset = utf-8"); PrintWriter out = Response.getWriter (); out.println ("<! doctype html public/"-// w3c // dtd html 4.01 transitório // en/">"); out.println ("<html>"); out.println ("<head> <title> CHX Cloud Álbum </ititle> </head>"); out.println ("<body>"); out.println ("<tabela borda = '1px; duplo;#ff0000'>"); out.println ("<tr>"); out.println ("<tr>"); out.println ("<td> Nome do arquivo </td>"); out.println ("<td> upload time"); out.println ("<td> arquivo </td>"); out.println ("<td> Descrição </td>"); out.println ("<td> operação </td>"); out.println ("</tr>"); String tdwh = "style = 'width: 200px; altura: 200px;'"; // mostra todas as fotos photodao dao = photodaofactory.getphotodao (); Lista <Photomodel> fotos = dao.getall (); para (Foto Photomodel: Fotos) {String filename = photo.getRealName (); String time = foto.getDateTime (); // saída de string de imagem Path = request.getContextPath () + "/photos/" + foto.getDir () + "/" + foto.getuuid () + foto.getext (); // System.out.println (caminho); //myphoto/photos//7/c/a1237a48a6aa451cb22fa78b15bafcea.jpg string img = "<a href = '" + path + "'> <img src = '" + "'/> </a>"; String desc = foto.getDesc (); String delstr = "<a href = '/myphoto/servlet/delservlet? Uuid =" + foto.getuuid () + "'> delete </a>"; String downstr = "<a href = '/myphoto/servlet/donServlet? Uuid =" + foto.getuuid () + "' '> 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 ("</tabela"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.Close (); }}Excluir arquivo - delservlet.java
pacote cn.hncu.servlets; importar java.io.ioException; importar java.io.printwriter; importar javax.servlet.servletexception; importar javax.servlet.http.httpSletLe; import javax.servlet.http.httlestlestlest; javax.servlet.http.httpServletResponse; importar cn.hncu.domain.photomodel; importação cn.hncu.photodao.dao.photodao; importação cn.hncu.photodao.factory.photodaofactory; public ClasslernVless Extlvlet Extvlenst Extvlenstled (PlowDoTodaOffort; PublicOnVlends) Fotodaofactory.getphotodao (); Public void Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {DoPost (solicitação, resposta); } public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {string uuid = request.getParameter ("uuid"); String ip = request.getRemoTeaddr (); Response.setContentType ("Texto/html; charset = utf-8"); PrintWriter out = Response.getWriter (); Foto de fotomodel = dao.getSingleByuuid (uuid); if (foto! = null) {if (! foto.getip (). igual a (ip)) {out.print ("<h1> você não tem permissão para excluir este arquivo!!! </h1>"); out.print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); retornar ; } // 1. Excluir informações no banco de dados boolean boo = dao.deletexml (uuid); if (boo) {string filename = "fotos/"+foto.getDir ()+"/"+photo.getuuid ()+foto.getext (); String pathfilename = getServletContext (). GetRealPath (nome do arquivo); if (Dao.DeleteFile (PathFileName)) {// redireciona para a página do álbum Response.sendRedirect ("/myphoto/Cloudphoto? pwd = chx"); } else {out.print ("<H1> não pode ser excluído do servidor, o arquivo está sendo ocupado !!! </h1>"); out.print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); }} else {out.print ("<H1> O arquivo não existe mais !!! </h1>"); out.print ("<a href = 'javascript: history.go (-1)'> retornar à página anterior </a>"); }}}}Download Arquivo -Downservlet.java
pacote cn.hncu.servlets; importar java.io.fileInputStream; importar java.io.ioException; importar java.io.inputStream; importar java.io.outputStream; importexception.net.net.urlencoder; import javax.Servlet.ServTeTexception; importexception.Net.Net.Rencoder; javax.servlet.http.httpServletReQuest; importar javax.servlet.http.httpServletResponse; importar cn.hncu.main.photomodel; import cph.hncu.photodao.daoo.photodao; import cph.hnncu.photodao.daoo.photodao; importação; OffServlet estende httpServlet {private photodao dao = fotodaofactory.getphotodao (); Public void Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {DoPost (solicitação, resposta); } public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {string uuid = request.getParameter ("uuid"); System.out.println (UUID); Foto de fotomodel = dao.getSingleByuuid (uuid); System.out.println (foto); if(photo!=null){ //Set the response header--Content Receiver--When the browser sees this response header, it will open the download program it thinks is //(If Thunder is recognized, Thunder will automatically open, if not, a "Save File As" dialog box will be opened) response.setContentType("application/force-download"); String realname = foto.getRealName (); String agent = request.getheader ("user-agent"); System.out.println (agente); if (agent.indexof ("mozilla")! =-1) {// Firefox Browser Response.setheader ("Content-Disposition", "Applement; filename ="+ new String (realname.getBytes ("GB2312"), "iso-8859-1"); } else {// Resolva o problema dos chineses distorcidos (basta usar a seguinte frase para codificar o nome do arquivo) realname = urlencoder.encode (nome real, "utf-8"); // use o mecanismo de codificação especificado para converter a string em formato Application/X-WWW-Form-UrlCoded. Response.setheader ("Content-Disposition", "Anexamento; nome do arquivo =/" "+realname+"/""); // Nota: "cttachment;" não pode estar faltando, caso contrário, o navegador será aberto diretamente em uma nova janela} string filename = "photos/"+photo.getDir ()+"/"+foto.getuuid ()+photo.geText (); String pathfilename = getServletContext (). GetRealPath (nome do arquivo); InputStream in = new FileInputStream (PathFileName); OutputStream out = Response.getOutputStream (); byte buf [] = novo byte [2048]; int len = 0; while ((len = in.read (buf))! =-1) {out.write (buf, 0, len); } out.close (); in.Close (); } else {Response.SetContentType ("text/html; charset = utf-8"); Response.getWriter (). println ("<H1> Este arquivo foi excluído </h1>"); }}}Resultados da demonstração
Não vou demonstrar isso, há fotos na frente e eu dei todos os códigos de origem. Se você estiver interessado, pode fazer algumas melhorias sozinho.
De fato, isso também pode fazer upload de qualquer outro tipo de arquivo, porque não temos um nome de sufixo protetor e usamos o streaming de caracteres para transmiti -lo, e ele não será distorcido (ele pode ser processado como um disco em nuvem ~~)! !
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.