ليس لدي ما أفعله ، لذلك كتبت servlet لتنفيذ وظيفة التحميل والتنزيل. بعد بدء الخدمة ، يمكنك أن تكون خادم ملفات صغير في LAN.
1. التحضير
قم بتنزيل حزمتين جرة:
المشاع filepload -1.3.1.jar
العموم-IO-2.2.JAR
2. إنشاء مشروع ويب
مشروعي يسمى: Z-Upload
3. تكوين 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_3_0.xd <splay-name> z-upload </display-name> <vishlet> <Sradlet-Name> UploadService </servlet-name> <stervlet-class> com.syz.servlet.uploadservice </servlet-class> </servlet> </servlet-mapping> </web-app>
من التكوين أعلاه ، يمكننا أن نرى أن فئة Servlet الخاصة بي هي تحميل خدمة ، وعنوان URL المطابق هو /*، مما يعني مطابقة جميع عناوين URL للوصول.
4. اكتب فئة 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.pintwriter ؛ java.util.date ؛ import java.util.iterator ؛ import java.util.list ؛ import javax.servlet.servletcontext ؛ import javax.servlet.servletexception ؛ import javax.servlet.http.httpservlet ؛ javax.servlet.http.httpservletresponse ؛ import org.apache.commons.fileupload.fileItem ؛ import org.apache.commons.fileupload.filePloAdexception ؛ import org.commons.fileud. org.apache.commons.fileupload.disk.diskfileItemFactory ؛ import org.apache.commons.fileupload.servlet.servletfilePload ؛ فئة public uploadservlet يمتد httpservlet {public static final string = "/list" ؛ نموذج السلسلة النهائية الثابتة العامة = "/form" ؛ السلسلة النهائية الثابتة العامة = "/handle" ؛ السلسلة النهائية الثابتة العامة = "/download" ؛ السلسلة النهائية الثابتة العامة الحذف = "/delete" ؛ السلسلة النهائية الثابتة العامة expload_dir = "/expload" ؛ استاتيكي خاص نهائي الطويل المسلسل = 2170797039752860765L ؛ تنفيذ Public Void (httpservletrequest req ، httpservletresponse resp) يلقي servletexception ، ioException {system.out.println ("execute ...") ؛ System.out.println ("------------ begin ---------------") ؛ req.setcharacterencoding ("UTF-8") ؛ سلسلة مضيف = req.getRemoteHost () ؛ System.out.println ("Host:" + Host) ؛ String uri = req.getRequesturi () ؛ System.out.println ("uri:" + uri) ؛ servletContext servletContext = this.getServletConfig () .getServletContext () ؛ // المسار الأساسي لتحميل سلسلة الملفات basepath = servletContext.getRealPath (epload_dir) ؛ // Context Path String ContextPath = servletContext.getContextPath () ؛ System.out.println ("ContextPath:" + ContextPath) ؛ // المسار بعد اعتراض عمل سلسلة السياق = uri.substring (contextpath.length ()) ؛ System.out.println ("الإجراء:" + إجراء) ؛ // يتم إجراء معالجة مختلفة وفقًا لإجراءات مختلفة if (action.equals (form)) {form (contextpath ، resp) ؛ } if if (action.equals (handle)) {boolean isMultiPart = servletfileUpload.ismultipartContent (req) ؛ system.out.println ("isMultipart:" + isMultipart) ؛ if (! isMultipart) {return ؛ } diskfileItemFactory Factory = new DiskfileItemFactory () ؛ مستودع الملف = (ملف) servletContext .getAttribute (servletContext.tempdir) ؛ system.out.println ("ropository:" + ropository.getabsolutepath ()) ؛ System.out.println ("BasePath:" + basepath) ؛ Factory.SetSizethReshold (1024 * 100) ؛ Factory.SetRepository (مستودع) ؛ servletfileupload تحميل = جديد servletfileupload (المصنع) ؛ // إنشاء مستمع Progressener ProgressListener = new ProgressListener () {public void update (pbytesread long ، pcontentLength ، int pitems) {system.out.println ("حجم الملف الحالي:" + pcontentLength + "/t تمت معالجته بالفعل:" + pbytesread) ؛ }} ؛ expload.setProgressListener (ProgressListener) ؛ قائمة <FileItem> عناصر = null ؛ جرب {عناصر = epload.parserequest (req) ؛ System.out.println ("العناصر حجم:" + items.size ()) ؛ iterator <IpileItem> item = items.iterator () ؛ بينما (ite.hasnext ()) {fileItem item = item.next () ؛ if (item.isformfield ()) {// handle formfield} else {// handle file string fieldName = item.getFieldName () ؛ اسم ملف السلسلة = 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) ؛ ملف الملف = ملف جديد (BasePath + "/" + filename + "_" + getSuffix ()) ؛ // item.write (file) ؛ inputStream in = item.getInputStream () ؛ OutputStream Out = fileOutputStream جديد (ملف) ؛ بايت [] ب = بايت جديد [1024] ؛ int n = 0 ؛ بينما ((n = in.read (b))! = -1) {out.write (b ، 0 ، n) ؛ } out.flush () ؛ in.close () ؛ out.close () ؛ }} // إعادة التوجيه إلى صفحة قائمة الملفات بعد معالجة سلسلة HREF1 = ContextPath + List ؛ Resp.SendRedirect (HREF1) ؛ } catch (fileuploadexception e) {eprintStackTrace () ؛ } catch (استثناء e) {E.PrintStackTrace () ؛ }} آخر إذا (Action.equals (list)) {list (ContextPath ، BasePath ، resp) ؛ } if if (action.equals (download)) {string id = req.getParameter ("id") ؛ System.out.println ("id:" + id) ؛ if (id == null) {return ؛ } ملف الملف = ملف جديد (BasePath) ؛ file [] list = file.listfiles () ؛ int len = list.length ؛ العلم المنطقي = خطأ ؛ لـ (int i = 0 ؛ i <len ؛ i ++) {file f = list [i] ؛ سلسلة fn = f.getName () ؛ if (f.isfile () && fn.lastindexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")) ؛ if (id.equals (fid)) {download (f ، resp) ؛ العلم = صحيح ؛ استراحة؛ }}} if (! flag) {notfound (contextpath ، resp) ؛ }} آخر إذا (Action.equals (delete)) {string id = req.getParameter ("id") ؛ System.out.println ("id:" + id) ؛ if (id == null) {return ؛ } ملف الملف = ملف جديد (BasePath) ؛ file [] list = file.listfiles () ؛ int len = list.length ؛ العلم المنطقي = خطأ ؛ لـ (int i = 0 ؛ i <len ؛ i ++) {file f = list [i] ؛ سلسلة fn = f.getName () ؛ if (f.isfile () && fn.lastindexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")) ؛ if (id.equals (fid)) {f.delete () ؛ العلم = صحيح ؛ استراحة؛ }}} if (flag) {// إعادة توجيه إلى صفحة قائمة الملفات بعد معالجة سلسلة href1 = contextpath + list ؛ Resp.SendRedirect (HREF1) ؛ } آخر {notfound (contextpath ، resp) ؛ }} آخر {show404 (ContextPath ، resp) ؛ } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- printwriter out repr.getwriter () ؛ للعودة إلى قائمة الملفات </b> ") ؛ out.write (" </body> ") ؛ out.write (" </html> ") ؛ out.close () Resp.GetWriter () ؛ Out.write ("<head> <title> نموذج </title> </head>") ؛ out.write ("<body>") ؛ out.write ("<b> <a href = '" + href1 + "'> انقر فوق </a> للعودة إلى قائمة الملفات </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 ("<type type = 'submit' value = 'expload'/> <br>") ؛ out.write ("</form>") ؛ out.write ("</body>") ؛ out.write ("</html>") ؛ out.close () ؛ } private void notfound (String ContextPath ، httpservletresponse resp) يلقي ioException {resp.setContentType ("text/html ؛ charset = utf-8") ؛ printWriter out = resp.getWriter () ؛ String Href1 = ContextPath + List ؛ out.write ("<html> <body> <b> فشل العملية! الملف غير موجود أو تم حذف الملف! <a href = '" + href1 + "'> انقر </a> للعودة إلى قائمة الملفات </b> </body> </tml>) ؛ out.close () ؛ } تنزيل void الخاص (ملف F ، httpservletResponse RESP) يلقي ioException {String fn = f.getName () ؛ اسم ملف السلسلة = 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:" + charsingFilename) ؛ resp.Setheader ("Disposition" ، "المرفق ؛ filename =" + encodingFilename) ؛ inputStream في = new FileInputStream (f) ؛ outputStream Out = resp.getOutputStream () ؛ بايت [] ب = بايت جديد [1024] ؛ int n = 0 ؛ بينما ((n = in.read (b))! = -1) {out.write (b ، 0 ، n) ؛ } out.flush () ؛ in.close () ؛ out.close () ؛ } قائمة void الخاصة (String ContextPath ، String BasePath ، httpservletresponse resp) يلقي ioException {String Href_u = contextpath + form ؛ Resp.SetContentType ("Text/Html ؛ charset = utf-8") ؛ printWriter out = resp.getWriter () ؛ out.write ("<html>") ؛ out.write ("<head> <title> قائمة </title> </head>") ؛ out.write ("<body>") ؛ out.write ("<b> أريد <a href = '" + href_u + "'> التحميل </a> </b> <br>") ؛ out.write ("<table border = '1' style = 'collapse: الانهيار ؛ العرض: 100 ٪ ؛ الهامش: 20px ؛'>") ؛ out.write ("<head>") ؛ out.write ("<tr>") ؛ out.write ("<h> الرقم التسلسلي </th> <h> اسم الملف </th> <th> العملية </th>") ؛ out.write ("</tr>") ؛ out.write ("</tr>") ؛ out.write ("<tbody>") ؛ ملف الملف = ملف جديد (BasePath) ؛ file [] list = file.listfiles () ؛ System.out .println ("BasePath:" + basepath + "/tlist.size:" + list.length) ؛ int len = list.length ؛ int no = 1 ؛ لـ (int i = 0 ؛ i <len ؛ i ++) {file f = list [i] ؛ System.out.println (i + "/t" + f.getName ()) ؛ سلسلة fn = f.getName () ؛ if (f.isfile () && fn.lastindexof ("_")> -1) {String filename = fn.substring (0 ، fn.lastindexof ("_")) ؛ معرف السلسلة = 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 (اسم الملف) ؛ sb.append ("</td>") ؛ sb.append ("<td>") ؛ sb.append ("<a href = '") ؛ SB.Append (HREF1) ؛ sb.append ("'> تنزيل </a> <a href ='") ؛ SB.Append (HREF2) ؛ sb.append ("'onClick =' return تأكيد (/" هل أنت متأكد من أنك تريد حذفه؟/") ؛"> حذف </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 dogge (httpservletrequest req ، httpservletresponse resp) يلقي servletexception ، ioException {system.out.println ("doget ...") ؛ تنفيذ (req ، resp) ؛ } public void dopost (httpservletrequest req ، httpservletresponse resp) يلقي servletexception ، ioException {system.out.println ("dopost ...") ؛ تنفيذ (req ، resp) ؛ } سلسلة خاصة getSuffix () {Date Date = New Date () ؛ SimpleDateFormat SDF = جديد spiStFormat ("YyyyMMDDHHMMSSSSSs") ؛ سلسلة لاحقة = sdf.format (التاريخ) ؛ عودة لاحقة. }}في الواقع ، يمكن لفئة ToildService تنفيذ طريقة الخدمة مباشرة دون تنفيذ أساليب DOGET و DOPOST.
لا أريد أن أشرح أي شيء عن servlets أعلاه ، ما عليك سوى قراءة الكود لنفسك.
5. مخطط التكاثر
1. مخطط هيكل المشروع
صفحة 2.404
/* سوف يتطابق مع جميع الأحرف الفارغة ، وبالتالي فإن المسار في الصورة سوف يتطابق ، والذي يظهر في آخر في الحكم IF في تحميل التحميل ، لأن الإجراء في هذا الوقت هو حرف فارغ.
3. صفحة قائمة الملفات
4.
5. تحميل
6. حذف
7. لا يمكن العثور على الملف. إذا لم يعد الملف موجودًا على الخادم عند النقر فوق حذف ، فستقوم بإدخال هذه الصفحة.
8. مشاريع رمز المصدر المعبأة وحزم الحرب
من بينها ، Z-Upload هو مشروع رمز المصدر Eclipse ، و Z-upload.war هي حزمة الحرب الجاهزة
لا يوجد سوى حزمتين جارتين في المشروع بأكمله ، و web.xml واحد وفئة Servlet واحدة. يمكنك نسخها من المقالة واختبارها. إذا كنت كسولًا ، فيمكنك تنزيله.
http://download.csdn.net/detail/yunsyz/9569680 ، تذكير خاص ، قم بتنزيله لمدة 1 نقطة.
ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.