No tengo nada que hacer, así que escribí un servlet para implementar la función de carga y descarga. Después de comenzar el servicio, puede ser un pequeño servidor de archivos en una LAN.
1. Preparación
Descargue dos paquetes jar:
Commons-FileUpload-1.3.1.Jar
Commons-io-2.2.Jar
2. Cree un proyecto web
Mi proyecto se llama: Z-Supload
3. Configurar web.xml
<? xml versión = "1.0" encoding = "utf-8"?> <web-app xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" " xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" <Spant-Name> Z-UPPload </splay-Name> <Servlet> <Servlet-name> uploadService </servlet-name> <ervlet-class> com.syz.servlet.uploadservice </servlet-class> </servlet> <ervlet-mapping> <ervlet> upoadservice </servlet-name> <s url-pattern>/*<</urbe> </url-name> </url> </url> <usl> </url-name> </servlet mapping> </beb-app>
Desde la configuración anterior, podemos ver que mi clase Servlet es SubloadService, y la URL coincidente es /*, lo que significa que coincide con todas las URL de acceso.
4. Escribir clase de servlet
paquete com.syz.servlet; import java.io.file; 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.text.sImpleTATA; java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletContex javax.servlet.http.httpServletResponse; import org.apache.commons.fileUpload.FileItem; import org.apache.commons.fileUpload.fileUploadException; importar org.apache.commons.fileupload.progresslistener; importar; import org.apache.commons.fileupload.disk.diskfileitemFactory; import org.apache.commons.fileupload.servlet.servletfileUpload; public class uploadServlet extiende httpservlet {public static final string list = "/list"; public static final String form = "/form"; public static final String Handle = "/Handle"; public static final String download = "/download"; public static final Final String Delete = "/Eliminar"; public static final String upload_dir = "/upload"; Private static final Long SerialVersionUid = 2170797039752860765l; public void Execute (httpservletRequest req, httpservletResponse resp) lanza ServletException, ioexception {System.out.println ("Ejecutar ..."); System.out.println ("------------ Comenzar ---------------"); req.setcharacterEncoding ("UTF-8"); String host = req.getRemoteHost (); System.out.println ("host:" + host); Cadena uri = req.getRequesturi (); System.out.println ("Uri:" + uri); ServletContext ServletContext = this.getServletConfig () .getServletContext (); // La ruta base para cargar la cadena de archivo basepath = servletContext.getRealPath (upload_dir); // Context String String contextPath = servletContext.getContextPath (); System.out.println ("ContextPath:" + contextPath); // ruta después de interceptar la cadena de contexto Action = uri.substring (contextPath.length ()); System.out.println ("Action:" + Action); // El procesamiento diferente se realiza de acuerdo con diferentes acciones if (Action.equals (Form)) {Form (contextPath, resp); } else if (action.equals (handle)) {boolean isMultipart = servletFileUpload.IsmultipartContent (req); System.out.println ("isMultipart:" + isMultipart); if (! isMultipart) {return; } DiskfileitemFactory factory = new DiskFileItemFactory (); File Repository = (File) ServletContext .getAttribute (servletContext.tempdir); System.out.println ("Repository:" + Repository.GetAbSolutePath ()); System.out.println ("BasePath:" + BasePath); Factory.setsizethreshold (1024 * 100); factory.setRepository (repository); ServletFileUpload upload = new ServLetFileUpload (fábrica); // Cree un escucha ProgressListener progressListener = new ProgressListener () {public void Update (Long pbytesread, long pContentLength, int pitems) {system.out.println ("tamaño de archivo actual:" + pcontentLength + "/t ya procesado:" + pbytesread); }}; upload.setProgressListener (ProgressListener); Lista <StilEitem> items = null; intente {elementos = upload.parserequest (req); System.out.println ("Tamaño de elementos:" + items.size ()); Iterator <StilEitem> item = items.iterator (); while (ite.hasnext ()) {fileItem item = item.next (); if (item.isformfield ()) {// manejar formfield} else {// manejar el archivo string fieldame = item.getFieldName (); Cadena filename = item.getName (); filename = filename.substring (filename.lastIndexof (file.separator) + 1); Cadena contentType = item.getContentType (); boolean isinmemory = item.isinMemory (); larga tamañoinbytes = item.getSize (); System.out.println (fieldName + "/t" + nombre de archivo + "/t" + contentType + "/t" + isinmemory + "/t" + sizeInbytes); Archivo archivo = nuevo archivo (basepath + "/" + nombre de archivo + "_" + getSuffix ()); // item.write (archivo); InputStream in = item.getInputStream (); OutputStream out = new FileOutputStream (archivo); byte [] b = nuevo byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); cercar(); out.close (); }} // redirigir a la página de la lista de archivos después de procesar cadena href1 = contextPath + list; resp.sendedirect (href1); } catch (FileUploadException e) {E.PrintStackTrace (); } catch (Exception e) {E.PrintStackTrace (); }} else if (acción.equals (list)) {list (contextPath, basepath, resp); } else if (action.equals (descargar)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Archivo archivo = nuevo archivo (basepath); Archivo [] list = file.listFiles (); int len = list.length; bandera booleana = falso; for (int i = 0; i <len; i ++) {archivo f = list [i]; Cadena fn = f.getName (); if (f.isfile () && fn.lastIndexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")); if (id.equals (fid)) {descargar (f, resp); bandera = verdadero; romper; }}} if (! flag) {nofound (contextPath, resp); }} else if (action.equals (delete)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Archivo archivo = nuevo archivo (basepath); Archivo [] list = file.listFiles (); int len = list.length; bandera booleana = falso; for (int i = 0; i <len; i ++) {archivo f = list [i]; Cadena fn = f.getName (); if (f.isfile () && fn.lastIndexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")); if (id.equals (fid)) {f.delete (); bandera = verdadero; romper; }}} if (flag) {// redirigir a la página de la lista de archivos después de procesar cadena href1 = contextPath + list; resp.sendedirect (href1); } else {nofound (contextpath, resp); }} else {show404 (contextpath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Printwriter out = resp.getwriter (); para volver a la lista de archivos </b> "); out.write (" </body> "); out.write (" </html> "); out.close ();} private void form (string contextPath, httpservletreSponse resp) lanza ioexception {resp.setSetContentTentType (" Text/html; Charset = uTf-8 "; resp.getwriter (); out.write ("<head> <title> Form </title> </head>"); out.write ("<body>"); out.write ("<b> <a href = '" + href1 + "'> haga clic en </a> para volver a la lista de archivos </b>"); out.write ("<Form Action = 'Handle' Method = 'Post' Enctype = 'multipart/form-data' style = 'margin-top: 20px;'>"); out.write ("<input name = 'file' type = 'file'/> <br>"); out.write ("<input type = 'subt' value = 'upload'/> <br>"); out.write ("</form>"); out.write ("</body>"); out.write ("</html>"); out.close (); } private notfound (String contextPath, httpservletResponse resp) lanza ioexception {resp.setContentType ("text/html; charset = utf-8"); PrintWriter out = resp.getwriter (); Cadena href1 = contextpath + list; out.write ("<html> <body> <b> falló! out.close (); } private void download (archivo f, httpservletResponse resp) lanza ioexception {string fn = f.getName (); Cadena filename = fn.substring (0, fn.lastindexof ("_")); System.out.println ("FileName:" + FileName); resp.reset (); resp.setContentType ("Application/Octet-stream"); String codingFileName = new String (FileName.getBytes ("GBK"), "ISO8859-1"); System.out.println ("EncodingFileName:" + EncodingFileName); resp.setheader ("Disposición de contenido", "Adjunto; FileName =" + EncodingFileName); InputStream in = new FileInputStream (f); OutputStream out = resp.getOutputStream (); byte [] b = nuevo byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); cercar(); out.close (); } Lista vacía privada (String contextPath, String BasePath, HttpServletResponse Res) lanza ioexception {string href_u = contextPath + form; resp.setContentType ("Text/html; charset = utf-8"); PrintWriter out = resp.getwriter (); out.write ("<html>"); out.write ("<HEAD> <title> list </title> </head>"); out.write ("<body>"); out.write ("<b> quiero <a href = '" + href_u + "'> cargar </a> </b> <br>"); out.write ("<table border = '1' style = 'border-colapso: colapso; ancho: 100%; margen-top: 20px;'>"); out.write ("<thead>"); out.write ("<tr>"); out.write ("<th> número de serie </th> <th> nombre del archivo </th> <th> operación </th>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); Archivo archivo = nuevo archivo (basepath); Archivo [] list = file.listFiles (); System.out .println ("BasePath:" + BasePath + "/tlist.size:" + list.length); int len = list.length; int no = 1; for (int i = 0; i <len; i ++) {archivo f = list [i]; System.out.println (i + "/t" + f.getName ()); Cadena fn = f.getName (); if (f.isFile () && fn.lastIndexof ("_")> -1) {string filename = fn.substring (0, fn.lastindexof ("_")); String id = fn.substring (fn.lastindexof ("_")); Cadena href1 = contextpath + descargar + "? Id =" + id; Cadena href2 = contextpath + eliminar + "? Id =" + id; StringBuilder sb = new StringBuilder (); sb.append ("<tr>"); sb.append ("<Td>"); sb.append (no ++); sb.append ("</td>"); sb.append ("<Td>"); sb.append (nombre de archivo); sb.append ("</td>"); sb.append ("<Td>"); sb.append ("<a href = '"); sb.append (href1); sb.append ("'> descargar </a> <a href ='"); sb.append (href2); sb.append ("'onClick =' return confirmar (/" ¿Estás seguro de que quieres eliminarlo?/"); '> Eliminar </a>"); sb.append ("</td>"); sb.append ("</tr>"); out.write (sb.ToString ()); }} out.write ("</tbody>"); out.write ("</table>"); out.write ("</body>"); out.write ("</html>"); out.close (); } public void doget (httpservletRequest req, httpservletResponse resp) lanza ServletException, ioexception {System.out.println ("Doget ..."); ejecutar (req, resp); } public void dopost (httpservletRequest req, httpservletResponse resp) lanza ServletException, ioexception {system.out.println ("dopost ..."); ejecutar (req, resp); } cadena privada getSuffix () {date date = new Date (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyymmddhhmmsssss"); String sufix = sdf.format (fecha); sufijo de devolución; }}De hecho, la clase de servicio de carga puede implementar directamente el método de servicio sin implementar los métodos DOGET y DOPOST.
No quiero explicar nada sobre los servlets anteriores, solo lea el código por ti mismo.
5. Diagrama de reproducción
1. Diagrama de estructura del proyecto
Página 2.404
/* coincidirá con todos los personajes nulos, por lo que la ruta en la imagen coincidirá, que aparece en el otro en el juicio if en SubloadService, porque la acción en este momento es un carácter nulo.
3. Página de lista de archivos
4. Página de formulario de carga
5. Descargar
6. Eliminar
7. El archivo no se puede encontrar. Si el archivo ya no existe en el servidor cuando hace clic en Eliminar, ingresará esta página.
8. Proyectos de código fuente empaquetado y paquetes de guerra
Entre ellos, Z-SuPload es el proyecto del código fuente de Eclipse, y Z-Supload.War es el paquete de guerra Ready
Solo hay dos paquetes JAR en todo el proyecto, un Web.xml y una clase de servlet. Puede copiarlo del artículo y probarlo. Si eres vago, puedes descargarlo.
http://download.csdn.net/detail/yunsyz/9569680, recordatorio especial, descargarlo por 1 punto.
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.