Je n'ai rien à faire, j'ai donc écrit un servlet pour implémenter la fonction de téléchargement et de téléchargement. Après avoir commencé le service, vous pouvez être un petit serveur de fichiers dans un LAN.
1. Préparation
Téléchargez deux packages JAR:
Commons-fileupload-1.3.1.jar
Commons-io-2.2.jar
2. Créer un projet Web
Mon projet s'appelle: z-upload
3. Configurer web.xml
<? xml version = "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" id = "webapp_id =" 3.0 " <frépison-name> z-upload </ display-name> <Serplet> <Servlet-Name> uploadService </ servlet-name> <servlet-class> com.syz.servlet.uploadService </ Servlet-Class> </ Servlet> <Servlet-Mapping> <servlet-name> uploadService </vrelet-name> <Url-Pattern> </ servlet-mapping> </ web-app>
À partir de la configuration ci-dessus, nous pouvons voir que ma classe de servlet est Téléchargement de téléchargement, et l'URL correspondante est / *, ce qui signifie correspondre à toutes les URL d'accès.
4. Écrivez le cours de servlet
package 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.printwriter; import java.text.simpledate; java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletcontext; import javax.servlet.servletException; import javax.servlet.http.httpservlet; import javax.servlet.http.http.httvletservlet; import; javax.servlet.http.httpservletResponse; import org.apache.commons.fileupload.fileItem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons. org.apache.commons.fileupload.disk.diskfileItemfactory; import org.apache.commons.fileupload.servlet.servletFileupload; public class uploadServlet étend httpsservlet {public static final list = "/ list"; public statique final string form = "/ form"; Public Static Final String Handle = "/ manche"; Public Static Final String Download = "/ Download"; Public static final String delete delete = "/ delete"; public static final string upload_dir = "/ upload"; Final statique privé long SerialVersionUID = 2170797039752860765L; public void execute (httpServLetRequest req, httpservletResponse resp) lève ServletException, ioException {System.out.println ("exécuter ..."); System.out.println ("------------ Begin ---------------"); req.SetcharAtterencoding ("UTF-8"); String host = req.getReMoteHost (); System.out.println ("hôte:" + hôte); String uri = req.getRequeSturi (); System.out.println ("URI:" + URI); ServletContext servletContext = this.getServletConfig () .getServletContext (); // le chemin de base pour télécharger la chaîne de fichiers BasEpath = servletContext.getRealPath (upload_dir); // String de contexte de contexte contextPath = servletContext.getContextPath (); System.out.println ("ContextPath:" + ContextPath); // Chemin après interception de la chaîne de contexte Action = uri.substring (contextPath.length ()); System.out.println ("Action:" + Action); // Le traitement différent est effectué en fonction de différentes actions if (action.equals (form)) {form (contextPath, resp); } else if (action.equals (manche)) {boolean isMultupart = servletFileUpload.ismulTipartContent (req); System.out.println ("IsMultupartill:" + Ismultupart); if (! IsMultupart) {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 (référentiel); ServletFileUpload upload = new ServletFileUpload (Factory); // Créer un écouteur ProgressListener ProgressListener = new ProgressListener () {public void Update (long pbytesRead, long pcontentLength, int Pittems) {System.out.println ("Taille actuelle du fichier:" + pcontentLength + "/ t déjà traité:" + pBytesRead); }}; upload.setProgressListener (ProgressListener); List <FeleItem> items = null; essayez {items = upload.parseRequest (req); System.out.println ("Taille des éléments:" + items.size ()); Iterator <FichierItem> item = items.Itator (); while (ite.hasnext ()) {fileItem item = item.next (); if (item.isformField ()) {// handle formField} else {// greatter file String fieldName = item.getFieldName (); String filename = item.getName (); filename = filename.substring (filename.lastIndexof (file.separator) + 1); String contentType = item.getContentType (); Boolean isInMemory = item.isinMemory (); long sizeInbytes = item.getSize (); System.out.println (FieldName + "/ T" + FileName + "/ T" + ContentType + "/ T" + ISINMEMORY + "/ T" + sizeInBytes); File file = new File (basepath + "/" + filename + "_" + getSuffix ()); // item.write (fichier); InputStream dans = item.getInputStream (); OutputStream out = new FileOutputStream (fichier); octet [] b = nouveau octet [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); joindre(); out.close (); }} // Rediriger vers la page de liste de fichiers après le traitement de la chaîne href1 = contextPath + list; resp.sendRedirect (HREF1); } catch (fileUpLoadexception e) {e.printStackTrace (); } catch (exception e) {e.printStackTrace (); }} else if (action.equals (list)) {list (contextPath, basepath, resp); } else if (action.equals (download)) {String id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Fichier file = nouveau fichier (baspath); File [] list = file.listFiles (); int len = list.length; booléen drapeau = false; for (int i = 0; i <len; i ++) {file f = list [i]; String fn = f.getName (); if (f.isfile () && fn.lastIndexof ("_")> -1) {string fid = fn.substring (fn.lastIndexof ("_")); if (id.equals (fid)) {download (f, resp); Flag = true; casser; }}} if (! Flag) {notFound (contextPath, resp); }} else if (action.equals (delete)) {String id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Fichier file = nouveau fichier (baspath); File [] list = file.listFiles (); int len = list.length; booléen drapeau = false; for (int i = 0; i <len; i ++) {file f = list [i]; String fn = f.getName (); if (f.isfile () && fn.lastIndexof ("_")> -1) {string fid = fn.substring (fn.lastIndexof ("_")); if (id.equals (fid)) {f.delete (); Flag = true; casser; }}} if (flag) {// rediriger vers la page de liste de fichiers après le traitement de la chaîne href1 = contextPath + list; resp.sendRedirect (HREF1); } else {notfound (contextPath, resp); }} else {show404 (contextPath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Printwriter out = resp.getwriter (); string href1 = contextPath + list; pour retourner à la liste de fichiers </b> "); out.write (" </gody> "); out.write (" </html> "); out.close ();} formulaire privé (string contextPath, httpservletResponse resp) lance ioException {resp.setContentType (" text / html; charset = utf-8 "); resp.getwriter (); string href1 = contextPath + list ;write ("<html>"); out.write ("<éad- head> <ititle> form </tapt> </ada>"); out.write ("<body>"); out.write ("<b> <a href = '" + href1 + "'> cliquez sur </a> pour revenir à la liste de fichiers </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 = 'soumi' value = 'upload' /> <br>"); out.write ("</ form>"); out.write ("</body>"); out.write ("</html>"); out.close (); } private void notfound (String ContextPath, httpServletResponse resp) lève ioException {resp.setContentType ("text / html; charset = utf-8"); Printwriter out = resp.getWriter (); String href1 = contextPath + list; out.write ("<html> <body> <b> L'opération a échoué! Le fichier n'existe pas ou le fichier a été supprimé! <a href = '" + href1 + "'> cliquez sur </a> pour revenir à la liste des fichiers </b> </body> </html>"); out.close (); } private void download (fichier f, httpsservletResponse res) lève ioException {string fn = f.getName (); String filename = fn.SubString (0, fn.lastIndexof ("_")); System.out.println ("FileName:" + FileName); resp.reset (); resp.setContentType ("Application / Octet-Stream"); String EncodingFileName = new String (filename.getBytes ("gbk"), "iso8859-1"); System.out.println ("EncodingFileName:" + EncodingFileName); resp.sethEader ("contenu-disposition", "attachement; filename =" + codingFileName); InputStream dans = new FileInputStream (f); OutputStream out = resp.getOutputStream (); octet [] b = nouveau octet [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); joindre(); out.close (); } Private void List (String ContextPath, String BasEpath, httpServletResponse resp) lève ioException {String href_u = contextPath + form; resp.setContentType ("text / html; charset = utf-8"); Printwriter out = resp.getWriter (); out.write ("<html>"); out.write ("<éad- head> <itle> list </title> </ head>"); out.write ("<body>"); out.write ("<b> je veux <a href = '" + href_u + "'> téléchargement </a> </b> <br>"); out.write ("<Table Border = '1' style = 'Border-Collapse: effondrement; largeur: 100%; margin-top: 20px;'>"); out.write ("<thead>"); out.write ("<tr>"); out.write ("<th> numéro de série </th> <th> Nom de fichier </th> <th> Operation </th>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); Fichier fichier = nouveau fichier (basepath); File [] 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 ++) {file f = list [i]; System.out.println (i + "/ t" + f.getName ()); String fn = f.getName (); if (f.sisfile () && fn.lastIndexof ("_")> -1) {String filename = fn.substring (0, fn.lastIndexof ("_")); String id = fn.substring (fn.lastIndexof ("_")); String href1 = contextPath + téléchargement + "? Id =" + id; String href2 = contextPath + delete + "? Id =" + id; StringBuilder sb = new StringBuilder (); SB.APPEND ("<TR>"); sb.append ("<td>"); SB.APPEND (NO ++); sb.append ("</td>"); sb.append ("<td>"); SB.APPEND (nom de fichier); sb.append ("</td>"); sb.append ("<td>"); sb.append ("<a href = '"); SB.APPEND (HREF1); SB.APPEND ("'> Télécharger </a> <a href ='"); SB.APPEND (HREF2); sb.append ("'onclick =' return confirm (/" êtes-vous sûr de vouloir le supprimer? / "); '> supprimer </a>"); sb.append ("</td>"); sb.append ("</tr>"); out.write (sb.toString ()); }} out.write ("</ tBody>"); out.write ("</pally>"); out.write ("</body>"); out.write ("</html>"); out.close (); } public void doGet (httpservletRequest req, httpservletResponse resp) lève ServletException, ioException {System.out.println ("doget ..."); exécuter (req, resp); } public void doPost (httpsservletRequest req, httpservletResponse resp) lève ServletException, ioException {System.out.println ("dopost ..."); exécuter (req, resp); } private String getSuffix () {date date = new Date (); SimpledateFormat sdf = new SimpledateFormat ("yyyymmddhhmmsssss"); String suffix = sdf.format (date); suffixe de retour; }}En fait, la classe UploadService peut implémenter directement la méthode de service sans implémenter les méthodes DoGet et DoPost.
Je ne veux rien expliquer sur les servlets ci-dessus, il suffit de lire le code par vous-même.
5. Diagramme de reproduction
1. Diagramme de structure du projet
Page 2.404
/ * correspondra à tous les caractères nuls, donc le chemin de l'image correspondra, ce qui apparaît dans le jugement IF dans le service de téléchargement, car l'action en ce moment est un caractère nul.
3. Page de liste de fichiers
4. Télécharger la page du formulaire
5. Télécharger
6. Supprimer
7. Le fichier ne peut être trouvé. Si le fichier n'existe plus sur le serveur lorsque vous cliquez sur Supprimer, vous entrerez cette page.
8. Projets de code source emballés et packages de guerre
Parmi eux, Z-upload est le projet Eclipse Source Code, et Z-upload.war est le package Ready War
Il n'y a que deux packages JAR dans l'ensemble du projet, un web.xml et une classe de servlet. Vous pouvez le copier à partir de l'article et le tester. Si vous êtes paresseux, vous pouvez le télécharger.
http://download.csdn.net/detail/yunsyz/9569680, rappel spécial, téléchargez-le pour 1 point.
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.