Al escribir una versión Java de Simple Cloud Album, las funciones implementadas son:
Los usuarios pueden cargar uno a varios archivos a la vez.
Los usuarios pueden descargar imágenes cargadas por otros.
Los usuarios pueden ver imágenes de todos los demás.
Los usuarios solo pueden eliminar imágenes cargadas a través de su propia IP.
Técnicas utilizadas:
Carga y descarga de archivos, modo de diseño, DOM4J, XPATH, etc.
Veamos las siguientes dos páginas:
Código fuente:
web.xml:
<? xml versión = "1.0" encoding = "utf-8"?> <web-app versión = "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"> <laction-name> </siple-name> <ervlet> <ervlet-name> uploadservlet </servlet> <Servlet-class> cn.hncu.servlets.uploadservlet </servlet-class> </servlet> <servlet> <servlet-name> cloudphotoservlet </servlet-name> <ervlet-class> cn.hncu.servlets.cloudphotoservleteLEn <servlet-class>cn.hncu.servlets.DownServlet</servlet-class> </servlet> <servlet> <servlet-name>DelServlet</servlet-name> <servlet-class>cn.hncu.servlets.DelServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <Url-Tattern>/upload </sl-Pattern> </servlet-mapping> <ervlet-mapping> <ervlet-name> nubphotoservlet </servlet-name> <url-pattern>/nubphoto </sl-pattern> </servlet-mapping> <ervlet-mapping> <ervlet-mapping> <ervlet-name> downservlet </servlet-name>-niseM <Url-Tattern>/Servlet/Downservlet </url-Pattern> </servlet-mapping> <ervlet-mapping> <ervlet-name> delservlet </servlet-name> <url-pattern>/servlet/delservlet </sl-pattern> </servlet-mapping> <bequey-file-list> <belliente-file> índice.jsp </shelve-cille> </Welcome-File-List> </beb-app>
index.jsp:
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <! DocType html público "-// w3c // dtd html 4.01 transitional // en"> <html> <thead> <title> chx Cloud Clum </title> <script Type = "Text/javasIsCripter" (torte) input.ParentElement.ParentElement.ParentElement; // table.nodename tbody table.removechild (input.ParentElement.ParentElement); } var t = 1; función addfile (input) {tr = input.ParentElement.ParentElement; //alert(tr.nodeName); var str = "<td> seleccione archivo: </td>"+ "<td> <input type = 'file' name = 'file"+ t+ "'> </td>"+ "<td> archivo descripción: </td>"+ "<td> <input type = 'text' name = 'text"+ t+ "'> </td>"+ "<td> <typy = 'button' value 'value' onClick = 'delfile (this)'> </td> "; tr.insertadjacenthtml ("antes de Begin", str); } function Move () {window.location.href = "/myphoto/cloudphoto"; } </script> <style type = "text/css"> #font {color: rojo; } </style> </head> <body> <h1> <font id = "font"> álbum upload: </font> </h1> <form de action = "/myphoto/upload" método = "post" enctype = "multipart/form-data"> <tr> <tr> <tr> <td> seleccionar archivo: </td> <td> <put type = "file =" nombre "n. <TD> Descripción del archivo: </td> <td> <input type = "text" name = "text1"> </td> <td> <input type = "button" value = "eliminar archivo" onclick = "delfile (this)"> </td> </tr> <tr> <td colspan = 2> <input type = "Subting" Value = "Upload File" <<ty td>>>> cicle>> caj <input type = "button" value = "add file" onClick = "addFile (this)"> </td> </tr> </table> </form> <form de action = "/myphoto/cloudphoto" métode = "post" entrype = "multipart/formy-data"> <table> <tr> <td colspan = 5> <put type = "subsit" value = "value =" value = "" Value = "Value =" Value "Enter the Cloud the Cloud the Cloud the Cloud the Cloud the Cloud the Cloud" álbum " onClick = "Move ()"> </td> </tr> </table> </form> </body> </html>Photo.xml:
<? xml versión = "1.0" encoding = "utf-8"?> <totos> </fotos>
Myutils.java:
paquete 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.randomuid (). Tostring (). } / ** * @param uuid * @return obtenga la ruta rota a través de uuid * / public static string getDir (string uuid) {string dir1 = integer.toHexString (uuid.hashcode () & 0xf); String dir2 = integer.toHexString ((uuid.hashcode () y 0xf0) >> 4); return "/"+dir1+"/"+dir2; } // Formato de fecha en la fecha estatica privada SimpledateFormat sdf = new SimpleDateFormat ("yyyyy año mm mes dd fecha hh: mm: ss"); / *** @return Devuelve la fecha y la hora al cargar*/ public static String getCurrentDateTime () {return sdf.format (new date ()); }}Dom4jfactory.java:
paquete cn.hncu.utils; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileOutputStream; import java.io.ioException; import java.io.unsupportedEncodeNingException; import org.dom4j.document; import og.om4j.document; importación; org.dom4j.element; import org.dom4j.node; import org.dom4j.io.saxreader; import org.dom4j.io.xmlwriter; public class dom4jfactory {documento estático privado dom = null; ruta de cadena estática privada; // Bloque estático! ¡Solo correrá una vez! La característica es que cuando la clase se carga, está estática {try {saxreader sax = new saxreader () se ejecuta; // Debido a que nuestros recursos se han publicado desde Myelipse hasta el servidor Tomcat, es diferente del proyecto Pure Java original. // Use la clase actual para encontrar su cargador de clase y luego obtener la ruta de recursos a través del cargador de clase. ruta = dom4jfactory.class.getClassLoader (). getResource ("Photo.xml"). GetPath (); // getClassLoader () Devuelve: Carga el cargador de clase de la clase o interfaz representada por este objeto // URL public getResource (nombre de cadena) Devuelve: Leer el objeto URL del recurso; Si no se puede encontrar el recurso, o la persona que llama no tiene suficiente permiso para obtener el recurso, devuelve nulo. // Este método primero busca el cargador de clase principal del recurso; Si el cargador de clase principal es nula, la ruta de búsqueda es la ruta del cargador de clase incorporado de la máquina virtual. // public String getPath () obtiene la parte de la ruta de esta URL. System.out.println (ruta); dom = sax.read (nuevo FileInputStream (ruta)); } Catch (FileNotFoundException e) {Throw New RuntimeException (e); } catch (DocumentException e) {Throw New RuntimeException (e); }} / ** * @return obtenga el documento del álbum * / public static document getDocument () {return dom; } / ** * Guardar photo.xml y guardar en local * / public static boolean save () {try {xmlwriter w = new XmlWriter (new FileOutputStream (Path)); w.write (DOM); w.close (); devolver verdadero; } catch (UnsupportedEncodingException e) {return false; } catch (FileNotFoundException e) {return false; } catch (ioException e) {return false; }} public static static boolean del (string uuid) {nodo nodo = dom.selectsinglenode ("[@uuid = '"+uuid+"']"); if (node == null) {return false; } node.getParent (). remove (nodo); devolver verdadero; } / *** test* @param args* / public static void main (string [] args) {system.out.println (getDocument ()); }}Photomodel.java - Objeto de valor
paquete cn.hncu.domain;/*** Value Object Encapsulation* @author Chen Haoxiang* 2016-7-7-24*/public class Photomodel {private String uuid; // uuid private string realName = ""; // El nombre de archivo real de la imagen (nombre de archivo al momento de la carga privada). cargar archivo de archivo privado string ip; // La cadena privada IP del cargador Desc; // El archivo Descripción 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 = descr; } @Override public String toString () {return "Photomodel [uuid =" + uuid + ", realName =" + realName + ", ext =" + ext + ", dir =" + dir + ", datTime =" + datetime + ", ip =" + ip + ", desc =" + descor + "]; }}Photodao.java:
paquete cn.hncu.photodao.dao; import java.util.list; import cn.hncu.domain.photomodel; interfaz public photodao { / *** @param photo* @return save data* / public boolean save (fotomodel Photo); / *** @return Devuelve toda la información de la imagen*/ Lista pública <Photomodel> getall (); / *** @param uuid* @return Encuentre el objeto de valor encapsulado a través de uuid*/ public photomodel getSingleByUuid (string uuid); / ** * @param uuid * @return Elimine la información de la imagen en fotos.xml a través de uuid */ public boolean deletExml (string uuid); / ** * @param dir * @return Elimine la información de la imagen en el disco del servidor a través de la ruta */ public boolean deletefile (string pathFileName);}Photoserimpl.java:
paquete cn.hncu.photodao.impl; import java.io.file; import java.util.arrayList; import java.util.iterator; import java.util.list; import org.dom4j.Document; import odom4j.Element; import org.dom4j.node; import cn.hncu.domain.photomel; importar; importación; importación; importación; cn.hncu.photodao.dao.photodao; import cn.hncu.utils.dom4jFactory; public class PhotoserImpl implementa Photodao {@Override public boolean save (Photomodel Photo) {Document DOM = DOM4JFactory.getDocument (); Elemento root = dom.getrooTelement (); // Agregar elemento de atributo p = root.addelement ("foto"); p.addattribute ("uuid", foto.getuuid ()); p.addattribute ("RealName", Photo.getRealName ()); p.addattribute ("DateTime", Photo.getDateTime ()); p.addattribute ("ip", foto.getip ()); p.addattribute ("ext", photo.getext ()); p.addattribute ("dir", photo.getDir ()); p.AdDattribute ("Desc", Photo.getDesc ()); return dom4jfactory.save (); } @Override Public List <Photomodel> getAll () {list <Photomodel> list = new ArrayList <Photomodel> (); Documento DOM = DOM4JFactory.getDocument (); Elemento root = dom.getrooTelement (); Iterador <ememem> it = root.ElementIterator ("Photo"); // Obtenga el iterador del elemento fotográfico a través de DOM4J, y también puede encontrar todas las fotos a través de xpath // list <node> lists = dom.selectnodes ("// photo [@uuid]"); // iterator <Node> it = lists.Iterator (); while (it.hasnext ()) {elemento e = it.next (); Photomodel Photo = new Photomodel (); Photo.setUuid (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 (foto); } Lista de retorno; } @Override public Photomodel getSingleByUuid (String UUID) {List <Photomodel> Photos = getAll (); para (Photomodel Photo: Photos) {if (Photo.getuuid (). Equals (UUID)) {return Photo; }} return null; } @Override public boolean DeletexMl (String UUID) {Document DOM = DOM4JFactory.getDocument (); Elemento e = (elemento) dom.selectsinglenode ("// photo [@uuid = '"+uuid.trim ()+"']"); return E.getParent (). Eliminar (e); } @Override public boolean DeleteFile (String PathFileName) {try {archivo archivo = nuevo archivo (pathFileName); if (file.exists ()) {file.delete (); } return verdadero; } capt (excepción e) {return false; }}}Photodaofactory.java:
paquete cn.hncu.photodao.factory; import cn.hncu.photodao.impl.photoseMpl;/*** Método de fábrica* @author Chen Haoxiang* 2016-7-7-24*/public class PhotodaOfActory {public static static getPhotodaoo () {return New PhotoserImpl (); }}UploadServlet.java:
package cn.hncu.servlets;import java.io.File;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 org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadException; import org.apache.comCom 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.utilililia; cn.hncu.utils.myutils; public class uploadServlet extiende httpservlet {public void doget (httpservletRequest request, httpServletResponse respuesta) lanza servletException, ioexception {respuesta.setContentType ("text/html; charset = utf-8"); Response.getWriter (). imprime ("<h1> Lo siento, esta página no admite obtener acceso! </h1>"); Response.getWriter (). print ("<a href = 'javascript: History.go (-1)'> Regreso a la página anterior </a>"); } public void dopost (httpservletRequest solicitud, respuesta httpservletreSponse) lanza ServletException, ioexception {Response.SetContentType ("Text/Html; Charset = UTF-8"); Final PrintWriter Out = Response.getWriter (); // Envío anti-Black-no-Multipart Forms // Utilice la herramienta de carga boolean boo = servletFileUpload.IsmultipartContent (solicitud); if (! boo) {out.print ("<h1> no admite el método de envío de las formas ordinarias! </h1>"); devolver; } Archivo archivo = nuevo archivo ("d:/photocache"); if (! file.exists ()) {file.mkdir (); } DiskFileItemFactory fifactory = new DiskFileItemFactory (1024*10, archivo); ServletFileUpload upload = new ServLetFileUpload (Fifactory); upload.setheaderEncoding ("UTF-8"); // Establecer el nombre del archivo Codificación de cadena Path = GetServletContext (). GetRealPath ("/Photos"); FileItem fi = null; intente {list <StilEitem> list = upload.parserequest (request); Photomodel Photo = new Photomodel (); // Encapsulación de datos --- 7 Propiedades se requieren Photo.SetRealName (""); int cont = 0; for (fileItem f: list) {if (cont! = 0 && cont%2 == 0 &&! Photo.getRealName (). Equals ("")) {Photo = new Photomodel (); // Recapsulación de re-data} fi = f; if (fi.isformfield ()) {// componente de formulario normal // Obtener el archivo Descripción String desc = fi.getString ("UTF-8"); Photo.setDesc (desc); //#1} else {// anti-Black 3-si el archivo no se selecciona en el componente del archivo if (fi.getSize () == 0) {Photo.SetRealName (""); cont ++; continuar; } Cadena filename = fi.getName (); FileName = FileName.Substring (FileName.lastIndexof ("//")+1); // nombre de archivo real Photo.SetRealName (FileName); //#2 String ext = FileName.Substring (FileName.LastIndexof (".")); // extension Photo.Setext (ext); //#3 Photo.SetDateTime (myUutils.getCurrentDateTime ()); //#4 Photo.Setip (request.getRemoteaddr ()); //#5 cadena uuid = myUtils.getuuid (); Photo.setUuid (uuid); //#6 Photo.SetDir (myUutils.getDir (uuid)); //#7 // interrumpir el archivo de directorio dfile = nuevo archivo (path+photo.getDir ()); if (! dfile.exists ()) {dfile.mkdir (); } fi.write (nuevo archivo (ruta+foto.getDir ()+"/"+Photo.getuuid ()+Photo.Getext ())); } cont ++; if (cont%2 == 0 &&! Photo.getRealName (). Equals ("")) {Photodao dao = PhotodaOfactory.getPhotodao (); boo = dao.save (foto); // Guardar en el disco - Método 2: fileUtils.CopyInputStreamToFile (in, nuevo archivo (filename2)); // ※ 2 ※ Almacenamiento del archivo de imagen en el servidor disco duro foto = new Photomodel (); // Reencapsulación}}} Catch (FileUploadeXception e) {E.PrintstArtTrace (); } catch (Exception e) {E.PrintStackTrace (); } finalmente {if (fi! = null) {fi.delete (); } if (dom4jfactory.save ()) {out.print ("<h1> ¡cargado con éxito! </h1>"); out.print ("<a href = 'javaScript: History.go (-1)'> Regrese a la página anterior </a>"); } else {out.print ("<h1> fallado! </h1>"); out.print ("<a href = 'javaScript: History.go (-1)'> Regrese a la página anterior </a>"); }}}}Mostrar todos los archivos -cloudphotoservlet.java
paquete 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.httservletRequest; javax.servlet.http.httpServletResponse; import cn.hncu.domain.photomodel; import cn.hncu.photodao.dao.photodao; import cn.hncu.photodao.factory.photodaOfactory; clase pública CloudphotOservlet extiende httpservlet {public void Void Void Void Void Void Void Void doget (httpservletRequest solicitud, respuesta httpservletResponse) lanza ServletException, ioException {String pwd = (string) request.getParameter ("pwd"); if ("chx" .equals (pwd)) {dopost (solicitud, respuesta); } else {Response.SetContentType ("Text/Html; Charset = UTF-8"); Response.getWriter (). imprime ("<h1> lo siento, no tiene permiso para acceder !!! </h1>"); }} public void dopost (httpservletRequest solicitud, httpservletreponse respuesta) arroja servletException, ioexception {respuesta.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 Cloud Album </title> </head>"); out.println ("<body>"); out.println ("<table border = '1px; double;#ff0000'>"); out.println ("<tr>"); out.println ("<tr>"); out.println ("<td> nombre de archivo </td>"); out.println ("<TD> tiempo de carga"); out.println ("<td> file </td>"); out.println ("<TD> Descripción del archivo </td>"); out.println ("<TD> operación </td>"); out.println ("</tr>"); Cadena tdwh = "style = 'width: 200px; altura: 200px;'"; // Mostrar todas las imágenes Photodao Dao = PhotodaOfactory.getPhotodao (); Lista <Photomodel> Photos = dao.getall (); for (Photomodel Photo: Photos) {String FileName = Photo.getRealName (); String time = photo.getDateTime (); // String String String Path = request.getContextPath () + "/Photos/" + Photo.getDir () + "/" + Photo.getuuid () + Photo.getext (); // System.out.println (ruta); // /myphoto/photos//7/c/a1237a48a6aaa451cb22fa78b15bafcea.jpg string img = "<a href = '" + ruta + "'> <img src = '" + ruta + "'/> </a>"; Cadena desc = foto.getDesc (); String delstr = "<a href = '/myphoto/servlet/delservlet? Uuid =" + photo.getuuid () + "'> eliminar </a>"; String Downstr = "<a href = '/myphoto/servlet/downservlet? Uuid =" + photo.getuuid () + "'> descargar </a>"; out.println ("<td" + tdwh + ">" + nombre de archivo + "</td>"); out.println ("<td" + tdwh + ">" + time + "</td>"); out.println ("<td" + tdwh + ">" + img + "</td>"); out.println ("<td" + tdwh + ">" + desc + "</td>"); out.println ("<td" + tdwh + ">" + delstr + "" + agudo abajo + "</td>"); out.println ("</tr>"); } out.println ("<tr>"); out.println ("</tr>"); out.println ("</table>"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); }}Eliminar el archivo - delservlet.java
paquete 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; import cn.hncu.domain.photomodel; import cn.hncu.photodao.dao.photodao; import cn.hncu.photodao.factory.photodaOfactory; clase pública delservlet extiende httpservlet {/////////// /daoOo DaoOo PhotodaOfactory.getPhotodao (); Public void doget (httpservletRequest, respuesta, respuesta httpservletResponse) lanza ServletException, ioexception {dopost (solicitud, respuesta); } public void dopost (httpservletRequest solicitud, respuesta httpservletResponse) lanza ServletException, ioexception {string uuid = request.getParameter ("uuid"); Cadena ip = request.getRemoteaddr (); respuesta.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> ¡No tienes permiso para eliminar este archivo!! </h1>"); out.print ("<a href = 'javaScript: History.go (-1)'> Regrese a la página anterior </a>"); devolver ; } // 1. Eliminar información en la base de datos boolean boo = dao.deletexml (uuid); if (boo) {String filename = "Photos/"+Photo.getDir ()+"/"+Photo.GetUUID ()+Photo.Getext (); String pathFileName = getServletContext (). GetRealPath (nombre de archivo); if (dao.deleteFile (pathFileName)) {// redirigir a la página de la página del álbum.sendedirect ("/myphoto/nubphoto? pwd = chx"); } else {out.print ("<h1> no se puede eliminar del servidor, ¡el archivo está siendo ocupado! </h1>"); out.print ("<a href = 'javascript: History.go (-1)'> Regrese a la página anterior </a>"); }} else {out.print ("<h1> ¡el archivo ya no existe! </h1>"); out.print ("<a href = 'javascript: History.go (-1)'> Regrese a la página anterior </a>"); }}}}Descargar archivo -downservlet.java
paquete cn.hncu.servlets; import java.io.fileInputStream; import java.io.ioException; import java.io.inputstream; import java.io.outputstream; import java.net.urlencoder; import javax.servlet.servletException; import javax.servlet.htp.htttttttttttttttttttttttttttttttttttpset; javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import cn.hncu.domain.photomodel; import cn.hncu.photodao.dao.photodao; import cn.hncu.photodao Downservlet extiende httpservlet {private Photodao dao = PhotodaOfactory.getPhotodao (); Public void doget (httpservletRequest, respuesta, respuesta httpservletResponse) lanza ServletException, ioexception {dopost (solicitud, respuesta); } public void dopost (httpservletRequest solicitud, respuesta httpservletResponse) lanza ServletException, ioexception {string uuid = request.getParameter ("uuid"); System.out.println (uuid); Photomodel Photo = dao.getSingleByUuid (uuid); System.out.println (foto); if (Photo! = Null) {// Establezca el encabezado de respuesta-receptor de contenido-Cuando el navegador ve este encabezado de respuesta, abrirá el programa de descarga que cree que es // (si el Thunder se reconoce, el trueno se abrirá automáticamente, si no, un archivo de diálogo "Guardar como" se abrirá) Respuesta). Cadena realName = Photo.getRealName (); String agent = request.getheader ("user-agent"); System.out.println (agente); if (agente.indexof ("Mozilla")! =-1) {// Firefox Browser Response.Setheader ("Content-Disposition", "Adjunto; FileName ="+ New String (RealName.getBytes ("GB2312"), "ISO-8859-1"); } else {// Resuelve el problema del chino confuso (solo use la siguiente oración para codificar el nombre del archivo) RealName = URLENCODER.Encode (RealName, "UTF-8"); // Use el mecanismo de codificación especificado para convertir la cadena en el formato de aplicación/X-www-URLCODEDED. respuesta.setheader ("Disposición de contenido", "Adjunto; FileName =/" "+RealName+"/""); // NOTA: "CTTACHMENT"; " No se puede faltar, de lo contrario, el navegador se abrirá directamente en una nueva ventana} String FileName = "Photos/"+Photo.getDir ()+"/"+Photo.Getuuid ()+Photo.Getext (); String pathFileName = getServletContext (). GetRealPath (nombre de archivo); InputStream in = new FileInputStream (PathFileName); OutputStream out = Response.getOutputStream (); byte buf [] = nuevo byte [2048]; int len = 0; while ((len = in.read (buf))! =-1) {out.write (buf, 0, len); } out.close (); cercar(); } else {Response.SetContentType ("Text/Html; Charset = UTF-8"); Response.getWriter (). println ("<h1> Este archivo se ha eliminado </h1>"); }}}Resultados de demostración
No demostraré esto, hay imágenes frente a ella y he dado todos los códigos de origen. Si está interesado, puede hacer algunas mejoras usted mismo.
De hecho, esto también puede cargar cualquier otro tipo de archivos, porque no tenemos un nombre de sufijo protector, y usamos la transmisión de personajes para transmitirlo, y no se distorsionará (¡se puede procesar como un disco de nube ~~)! !
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.