In diesem Artikel wird Beispiele verwendet, um die Verwendung von Commons-fileUpload.jar einzuführen. Apache commons-fileUpload.jar, um die Upload-Funktion von Dateien zu erleichtern. Der spezifische Inhalt ist wie folgt
Platzieren Sie die Commons-fileUpload.jar von Apache unter Web-inf/lib in der Anwendung und es ist bereit zu verwenden. Das folgende Beispiel zeigt, wie die Funktion "Datei -Upload" verwendet wird.
Die verwendete FileUpload -Version ist 1.2 und die Umgebung ist Eclipse3.3+myeClipse6.0. FileUpload basiert auf Commons IO. Bestimmen Sie vor dem Eintritt in das Projekt das JAR-Paket von Commons IO (unter Verwendung von commons-i-1.3.2.jar in diesem Artikel) unter Web-inf/lib/lib.
Dieser Artikel ist ein Beispielprojekt, das am Ende des Artikels im Anhang heruntergeladen werden kann.
Beispiel 1
Das einfachste Beispiel besteht darin, die Anfrage durch die statische Klasse ServletFileUpload zu analysieren. Die Fabrikklasse FileItemFactory verarbeitet alle Felder in Form der Mulipart -Klasse, nicht nur Dateifelder. GetName () erhält den Dateinamen, GetString () den Formulardateninhalt und IsFormfield () kann bestimmen, ob es sich um ein ordentliches Formular -Element handelt.
Demo1.html
<html> <kopf> <meta http-äquiv = "content-type" content = "text/html; charSet = gb18030"> <title> Datei-Upload </title> </head> <body> // Muss mehrteilige Formulardaten sein. <form name="myform" action="demo1.jsp" method="post" enctype="multipart/form-data"> Your name: <br> <input type="text" name="name" size="15"><br> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html>
Demo1.jsp
<%@ page Language = "java" contentType = "text/html; charSet = gb18030" pageCoding = "gb18030"%> <%@ page import = "org.apache.commons.FileUpload. import = "org.apache.commons.FileUpload.disk.*"%> <%@ page import = "java.util. Anfrage sind mehrteilige Formulardaten. if (ismultiPart == true) {FileItemFactory factory = new diskFileItemfactory (); // Erstellen Sie ein diskFileItemFactory -Objekt für die Anforderung und analysieren Sie die Anforderung durch sie. Nach der Ausführung des Parsens werden alle Formularelemente in einer Liste gespeichert. ServletFileUpload upload = new ServletFileUpload (fabrik); List <FileItem> items = Upload.ParSequest (Anfrage); Iterator <DileItem> itr = items.Iterator (); while (itr.hasnext ()) {FileItem item = (FileItem) itr.next (); // Überprüfen Sie, ob das aktuelle Projekt ein normales Formularprojekt oder eine Upload -Datei ist. if (item.isformfield ()) {// Wenn es sich um ein normales Formular -Element handelt, zeigen Sie den Formularinhalt an. String fieldname = item.getFieldname (); if (fieldname.equals ("name")) // Antwort auf type = "text" name = "name" out.print ("Der Feldname ist" + item.getString (); // Formularinhalte anzeigen. out.print ("<br>"); } else {// Wenn sie eine Datei hochladen, zeigen Sie den Dateinamen an. out.print ("Der Name des Upload -Dateins ist" + item.getName ()); out.print ("<br>"); }}} else {out.print ("Der EngeTePe muss Multipart/Form-Data sein"); }%> <html> <head> <meta http-äquiv = "content-type" content = "text/html; charset = gb18030"> <title> Datei-Upload </title> </head> <body> </body> </html> Ergebnis:
Der Feldname Isjeff
Der Name des Upload -Dateinamens ISD:/c Sprachtest Beispiel/Hausaufgaben Fragen.rar
Beispiel 2
Laden Sie zwei Dateien in das angegebene Verzeichnis hoch.
Demo2.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body> <form name="myform" action="demo2.jsp" method="post" enctype="multipart/form-data"> File1:<br> <input type="file" name = "myFile"> <br> Datei2: <br> <Eingabe type = "Datei" name = "myFile"> <br> <br> <Eingabe type = "surenden" name = "value =" commit "> </form> </body> </html>
Demo2.jsp
<%@ page Language = "java" contentType = "text/html; charSet = gb18030" pageCoding = "gb18030"%> <%@ page import = "org.apache.commons.FileUpload. import = "org.apache.commons.FileUpload.disk.*"%> <%@ page import = "java.util. boolean ismultiPart = servletFileUpload.ismultipartContent (Anfrage); if (ismultiPart == true) {try {FileItemFactory factory = new diskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (fabrik); List <FileItem> items = upload.ParSequest (Anfrage); // Alle Dateien Iterator <DileItem> itr = items.iterator () abrufen; while (itr.hasNext ()) {// train jeder Datei item = (FileItem) itr.next (); String Dateiname = item.getName (); // den Dateinamen inklusive Pfad if (Dateiname! = Null) {Datei fullfile = new Datei (item.getName ()); Datei SAREDFILE = NEUE Datei (UploadPath, fullfile.getName ()); item.write (savedFile); }} out.print ("Upload erfolgreich"); } catch (Ausnahme e) {e.printstacktrace (); }} else {out.println ("Der EngeType muss Multipart/Form-Data sein"); }%> <html> <head> <meta http-äquiv = "content-type" content = "text/html; charset = gb18030"> <title> Datei-Upload </title> </head> <body> </body> </html> Ergebnis:
Upload erfolgreich
Zu diesem Zeitpunkt sehen Sie die beiden Dateien, die Sie unter "D:/temp" hochgeladen haben.
Beispiel 3
Laden Sie eine Datei in das angegebene Verzeichnis hoch und begrenzen Sie die Dateigröße.
Demo3.html
<html><head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title></head><body> <form name="myform" action="demo3.jsp" method="post" enctype="multipart/form-data"> File:<br> <input type="file" name = "myFile"> <br> <br> <Eingabe type = "surenden" name = "sure" value = "commit"> </form> </body> </html>
Demo3.jsp
<%@ page Language = "java" contentType = "text/html; charSet = gb18030" pageCoding = "gb18030"%> <%@ page import = "org.apache.commons.FileUpload. import = "org.apache.commons.FileUpload.disk.*"%> <%@ page import = "java.util. Datei ("d: // temp"); // Dateiverzeichnis hochladen if (! UploadPath.Exists ()) {UploadPath.mkdirs (); } // Temporäre Dateiverzeichnisdatei temppathFile = new Datei ("d: // temp // buffer //"); if (! temppathfile.exists ()) {temppathFile.mkdirs (); } try {// Erstellen Sie eine Fabrik für Datentatelementelemente diskFileItemFactory factory = new diskFileItemfactory (); // Fabrikbeschränkungen Fabrik festlegen. SetSizethreshold (4096); // Puffergröße festlegen, hier ist 4KB Factory.setRepository (temppathfile); // Buffer -Verzeichnis einstellen // Erstellen Sie eine neue Datei hochladen Handler ServletFileUpload Upload = new ServletFileUpload (Factory); // Gesamtanforderungsgrößenkonstruktion einstellen. SetSizemax (4194304); // Maximale Dateigröße festlegen, hier ist 4MB LIST <DileItem> items = upload.ParSerequest (Anfrage); // Alle Dateien Iterator <DileItem> i = items.iterator () abrufen; while (i.hasnext ()) {FileItem fi = (FileItem) I.Next (); String Dateiname = fi.getName (); if (Dateiname! Datei SAREDFILE = NEUE Datei (UploadPath, FULLFILE .getName ()); fi.write (SavedFile); }} out.print ("Upload erfolgreich"); } catch (Ausnahme e) {e.printstacktrace (); }%> <html> <head> <meta http-äquiv = "content-type" content = "text/html; charset = gb18030"> <title> Datei-Upload </title> </head> <body> </body> </html> Beispiel 4
Verwenden Sie Servlet, um das Datei -Upload zu implementieren.
Upload.java
Paket com.zj.Sample; Import Java.io.file; Import Java.io.ioxception; import Java.util.iterator; Import Java.util.List; Import Javax.Servlet.ServletException; import Javax.servlet.http.httplet; import Javax.servlet.http.http.http.http.httpl. javax.servlet.http.httpServletResponse; import org.apache.commons.FileUpload.FileItem; import org.apache.commons.FileUpload.disk.diskFileTemfactory; import org. @SuppressWarnings ("Serial") öffentlicher Klasse Upload erweitert httpServlet {private String uploadPath = "d: // temp"; // Verzeichnis zum Hochladen von Dateien private String temppath = "d: // temp // buffer //"; // temporäre Dateiverzeichnisdatei temppathfile; @SuppressWarnings ("Unbekämpft") public void dopost (httpServletRequest-Anforderung, httpServletResponse-Antwort) löst IOException, ServletException aus {try {// Erstellen Sie ein Werk für diskbasierte Dateielemente diskfileMfactory = new diskFileTemFactory (); // Fabrikbeschränkungen Fabrik festlegen. SetSizethreshold (4096); // Puffergröße festlegen, hier ist 4KB Factory.setRepository (temppathfile); // Buffer -Verzeichnis einstellen // Erstellen Sie eine neue Datei hochladen Handler ServletFileUpload Upload = new ServletFileUpload (Factory); // Gesamtanforderungsgrößenkonstruktion einstellen. SetSizemax (4194304); // Maximale Dateigröße festlegen, hier ist 4MB LIST <DileItem> items = upload.ParSerequest (Anfrage); // Alle Dateien Iterator <DileItem> i = items.iterator () abrufen; while (i.hasnext ()) {FileItem fi = (FileItem) I.Next (); String Dateiname = fi.getName (); if (Dateiname! Datei SAREDFILE = NEUE Datei (UploadPath, fullfile.getName ()); fi.write (SavedFile); }} System.out.print ("Erfolg hochladen"); } catch (Ausnahme e) {// Die Fehlerseite kann gesprungen. }} public void init () löscht servleTException {Datei uploadFile = new Datei (UploadPath); if (! uploadfile.exists ()) {uploadFile.mkdirs (); } Datei temppathFile = new Datei (temppath); if (! temppathfile.exists ()) {temppathFile.mkdirs (); }}} Demo4.html
<html> <head> <meta http-equiv = "content-type" content = "text/html; charSet = gb18030"> <title> Datei-Upload </title> </head> <body> // action = "FileUtload" entspricht der Einstellung von <Url-Patter> in <servlet-maping in web.xml. <Formular name = "myForm" action = "FileUpload" method = "post" engType = "MultiPart/Form-Data"> Datei: <br> <Eingabe type = "Datei" name = "myFile"> <br> <br> <eingabe type = "subly" name = "subay =" value = "comment"> </body> </body> </html> </html> </html> </html>
web.xml
<servlet> <servlet-name> hochladen </servlet-name> <servlet-class> com.zj.Sampel
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.