Ich habe nichts zu tun, also habe ich einen Servlet geschrieben, um die Upload- und Download -Funktion zu implementieren. Nach dem Start des Dienstes können Sie ein kleiner Dateiserver in einem LAN sein.
1. Vorbereitung
Laden Sie zwei JAR -Pakete herunter:
Commons-fileUpload-1.3.1.Jar
Commons-io-2.2.jar
2. Erstellen Sie ein Webprojekt
Mein Projekt heißt: Z-Upload
A. Konfigurieren Sie web.xml
<? 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-app-app-app-app- = <diageinenname> z-Upload </display-name> <servlet> <servlet-name> uploadService </servlet-name> <Servlet-Klasse> com.syz.servlet.UploadService </Servlet-Class> </Servlet> <Servlet-Mapping> <Servlet-Name> UploadService </Servlet-Name> <Url-PATTER> </*/*</*/*</*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*</*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*</*/*/*: </Servlet-Mapping> </web-App>
Aus der obigen Konfiguration können wir feststellen, dass meine Servlet -Klasse Uploadservice ist und die passende URL /*ist, was bedeutet, dass alle Zugriffs -URLs übereinstimmen.
4. Schreiben Sie die Servlet -Klasse
Paket com.syz.servlet; import java.io.file; import Java.io.fileinputStream; Import Java.io.fileOutputStream; Import Java.io.ioException; importieren java.io.inputstream; importieren java.ioTream; java.util.date; import Java.util.iterator; import java.util.list; import Javax.servlet.servletContext; import Javax.servlet.servletException; importieren javax.servlet.http.httplet; javax.servlet.http.httpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.FileUpload.FileUploadexception; importieren org. org.apache.commons.FileUpload.disk.diskFileItemfactory; import org.apache.commons.FileUpload.Servlet.ServletFileUpload; öffentliche Klasse UploadServlet erweitert httpServlet {öffentliche statische endgültige String -Liste = "/list"; public static Final String Form = "/Form"; public static Final String handle = "/Handle"; public static final String download = "/download"; public static Final String String Delete = "/delete"; public static final String upload_dir = "/Upload"; Private Static Final Long Serialversionuid = 2170797039752860765L; public void execute (httpServletRequest req, httpServletResponse resp). System.out.println ("------------ Begin ---------------"); req.setcharactercoding ("utf-8"); String host = req.getremotehost (); System.out.println ("Host:" + Host); String uri = req.getRequesturi (); System.out.println ("uri:" + uri); ServletContext ServletContext = this.getServletConfig () .GetServletContext (); // Der Basispfad zum Hochladen der Datei String basepath = servletContext.getRealPath (Upload_Dir); // Context Path String contextPath = ServletContext.getContextPath (); System.out.println ("contextPath:" + contextPath); // Pfad nach Abschluss der Kontextstring -Aktion = uri.substring (contextPath.length ()); System.out.println ("Aktion:" + Aktion); // unterschiedliche Verarbeitung erfolgt nach verschiedenen Aktionen, wenn (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 (); Datei repository = (Datei) 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 (fabrik); // Erstellen eines Listener ProgressListener ProgressListener = new ProgressListener () {public void update (Long pByTesRead, Long pcontentLength, int Pitems) {System.out.println ("Aktuelle Dateigröße:" + pcontentLength + "/T bereits verarbeitet:" + pByTesRead); }}; Upload.SetProgressListener (ProgressListener); LIST <FileItem> items = null; try {items = upload.parsequest (req); System.out.println ("Elemente Größe:" + items.size ()); Iterator <FileItem> item = items.Iterator (); while (ite.hasnext ()) {FileItem item = item.Next (); if (item.isformfield ()) {// Formfield} else {// Dateistring -Feldname = item.getfieldname (); String Dateiname = item.getName (); Dateiname = Dateiname.substring (Dateiname.lastIndexof (Datei.Separator) + 1); String contentType = item.getContentType (); boolean isinmemory = issinmemory (); Long SizeInBytes = item.getSize (); System.out.println (fieldname + "/t" + Dateiname + "/t" + contentType + "/t" + isinmemory + "/t" + sizeInBytes); Datei Datei = neue Datei (Basepath + "/" + Dateiname + "_" + getuffix ()); // item.write (Datei); InputStream in = item.getInputStream (); OutputStream out = new FileOutputStream (Datei); Byte [] B = neues Byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); in.close (); out.close (); }} // Umleiten Sie die Dateilistenseite nach der Verarbeitung von String href1 = contextPath + Liste; resp.sendredirect (href1); } catch (FileUploadexception e) {e.printstacktrace (); } catch (Ausnahme 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; } Datei Datei = neue Datei (Basepath); Datei [] list = file.listfiles (); int len = list.length; boolesche Flagge = Falsch; für (int i = 0; i <len; i ++) {Datei 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 = wahr; brechen; }}} if (! Flag) {NotFound (contextPath, resp); }} else if (action.equals (delete)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Datei Datei = neue Datei (Basepath); Datei [] list = file.listfiles (); int len = list.length; boolesche Flagge = Falsch; für (int i = 0; i <len; i ++) {Datei 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 = wahr; brechen; }}} if (flag) {// Umleiten Sie nach der Verarbeitung von Zeichenfolge href1 = contextPath + list; resp.sendredirect (href1); } else {NotFound (contextPath, resp); }} else {show404 (contextPath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Printwrither out Um zur Dateiliste zurückzukehren </b> "); out.write (" </body> "); out.write (" </html> "); out.close ();} private void Form (String contextPath, httpServletRespectresponse) throws ioException {resp.setContentType (" text/html; charset resp.getWriter (); out.write ("<Head> <title> Form </title> </head>"); out.write ("<body>"); out.write ("<b> <a href = '" + href1 + "'> klicken </a> Um zur Dateiliste </b>" zurückzukehren "); out.write ("<form action = 'handle' method = 'post' engType = 'MultiPart/form-data' style = 'margin-top: 20px;'>"); out.write ("<input name = 'Datei' type = 'file'/> <br>"); out.write ("<Eingabe type = 'surenden' value = 'Upload'/> <br>"); out.write ("</form>"); out.write ("</body>"); out.write ("</html>"); out.close (); } private void NotFound (String contextPath, httpServletResponse resp) löscht ioException {resp.setContentType ("text/html; charset = utf-8"); Printwriter out = resp.getWriter (); String href1 = contextPath + liste; out.write ("<html> <body> <b> Operation fehlgeschlagen! Die Datei existiert nicht oder die Datei wurde gelöscht! out.close (); } private void download (Datei f, httpServletResponse resp) löst IOException {String fn = f.getName () aus; String Dateiname = fn.substring (0, fn.lastIndexof ("_")); System.out.println ("Dateiname:" + Dateiname); resp.reset (); resp.setContentType ("Anwendung/Oktett-Stream"); String codingFileName = new String (Dateiname.getBytes ("GBK"), "ISO8859-1"); System.out.println ("codingFileName:" + codingFileName); resp.setheader ("Inhaltsdisposition", "Anhang; Dateiname =" + codingFileName); InputStream in = neuer FileInputStream (f); OutputStream out = resp.getOutputStream (); Byte [] B = neues Byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); in.close (); out.close (); } private void -Liste (String contextPath, String Basepath, httpServletResponse resp) löscht ioException {String href_u = contextPath + Form; resp.setContentType ("text/html; charSet = utf-8"); Printwriter out = resp.getWriter (); out.write ("<html>"); out.write ("<kopf> <title> list </title> </head>"); out.write ("<body>"); out.write ("<b> Ich möchte <a href = '" + href_u + "'> hochladen </a> </b> <br>"); out.write ("<table border = '1' style = 'Border-Collapse: Zusammenbruch; Breite: 100%; Margin-Top: 20px;'>"); out.write ("<thead>"); out.write ("<tr>"); out.write ("<Th> Seriennummer </th> <Th> Dateiname </th> <th> operation </th>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); Datei Datei = neue Datei (Basepath); Datei [] list = file.listfiles (); System.out .println ("Basepath:" + basepath + "/tlist.size:" + list.length); int len = list.length; int no = 1; für (int i = 0; i <len; i ++) {Datei f = list [i]; System.out.println (i + "/t" + f.getName ()); String fn = f.getName (); if (f.isfile () && fn.lastIndexof ("_")> -1) {String fileName = fn.substring (0, fn.lastindexof ("_")); String id = fn.substring (fn.lastIndexof ("_")); String href1 = contextPath + download + "? 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 (Dateiname); sb.Append ("</td>"); sb.Append ("<td>"); sb.Append ("<a href = '"); sb.Append (href1); sb.append ("'> download </a> <a href ='"); sb.Append (href2); sb.append ("'onclick =' return bestätigen (/" Sind Sie sicher, dass Sie es löschen möchten?/"); '> löschen </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 dagget (httpServletRequest req, httpServletResponse resp) löst ServletException aus, ioException {System.out.println ("DOGGE ..."); ausführen (req, resp); } public void dopost (httpServletRequest req, httpServletResponse resp) löst ServletException aus, ioException {System.out.println ("Dopost ..."); ausführen (req, resp); } private String getuffix () {Datum date = new Date (); SimpleDateFormat SDF = new SimpledateFormat ("yyyymmddhmmssssss"); String -Suffix = SDF.Format (Datum); Rückkehrsuffix; }}Tatsächlich kann die Uploadservice -Klasse die Servicemethode direkt implementieren, ohne die DOGT- und Dopost -Methoden zu implementieren.
Ich möchte nichts über die oben genannten Servlets erklären und einfach den Code selbst lesen.
5. Reproduktionsdiagramm
1. Projektstrukturdiagramm
Seite 2.404
/* entspricht allen Null -Zeichen, sodass der Pfad im Bild übereinstimmt, der in der IF -Beurteilung im Uploadservice angezeigt wird, da die Aktion zu diesem Zeitpunkt ein Nullcharakter ist.
3. Dateiliste Seite
4. Formularseite hochladen
5. Download
6. Löschen
7. Die Datei kann nicht gefunden werden. Wenn die Datei beim Klicken auf dem Server bei Klicken nicht mehr vorhanden ist, geben Sie diese Seite ein.
8. Packaged Quellcodeprojekte und Kriegspakete
Unter ihnen ist Z-Upload das Eclipse-Quellcodeprojekt und z-upload.war ist das Ready War-Paket
Es gibt nur zwei JAR -Pakete im gesamten Projekt, ein Web.xml und eine Servlet -Klasse. Sie können es aus dem Artikel kopieren und testen. Wenn Sie faul sind, können Sie es herunterladen.
http://download.csdn.net/detail/yunsyz/9569680, spezielle Erinnerung, laden Sie es für 1 Punkt herunter.
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.