أولاً ، اسمحوا لي أن أقدم تحميل ملف
فئة الكيان
استيراد java.sql.timestamp ؛ / ** * * @described file refload class * */ public class upfile {private string id ؛ // id primary key بشكل عشوائي ينشئ سلسلة خاصة uuidname ؛ // uuid اسم ملف السلسلة الخاصة ؛ // اسم الملف السلسلة الخاصة SavePath ؛ // Save Path Private TimeStamp Leaptime ؛ // قم بتحميل وقت السلسلة الخاصة ؛ // وصف الملف اسم المستخدم الخاص بالسلسلة الخاصة ؛ // username public upfile () {super () ؛ } upfile العامة (معرف السلسلة ، السلسلة uuidname ، اسم ملف السلسلة ، سلسلة SavePath ، Timestamp exploadtime ، وصف السلسلة ، اسم المستخدم) {super () ؛ this.id = id ؛ this.uuidname = uuidname ؛ this.filename = اسم الملف ؛ this.savepath = SavePath ؛ this.uploadtime = التحميل ؛ this.description = الوصف ؛ this.username = اسم المستخدم ؛ } السلسلة العامة getDescription () {return description ؛ } السلسلة العامة getFilename () {return filename ؛ } السلسلة العامة getId () {return id ؛ } السلسلة العامة getSavePath () {return savePath ؛ } timestamp getuploadtime () {return exploadtime ؛ } السلسلة العامة getUserName () {return username ؛ } السلسلة العامة getUuidName () {return uuidname ؛ } public void setDescription (وصف السلسلة) {this.description = description ؛ } public void setFilename (اسم ملف السلسلة) {this.filename = filename ؛ } public void setId (string id) {this.id = id ؛ } public void setSavePath (String SavePath) {this.savePath = SavePath ؛ ) } public void setusername (string username) {this.userName = username ؛ } public void setUuidName (String uuidName) {this.uuidName = uuidName ؛ }}صفحة
<٪@ page language = "java" import = "java.util.*" pageencoding = "utf-8" ٪> <٪ string path = request.getContextPath () ؛ String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerPort ()+path+"/" ؛ ٪> <! doctype html public "-// w3c // dtd html 4.01 transitional // en"> <html> <head> <base href = "<٪ = basepath> <bragma> meta my jsp 'upload.jsp' page </title> http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "Expires" content = "0"> <meta http-equiv = "keywords" content = "keyword1 ، keyword2 ، keyword3"> <meta http-equiv = "description" content = type = "text/css" href = "styles.css">-> </head> <body> <h1> تحميل الملف </h1> <form action = "$ {pagecontext.request.contextpath}/upload" method = "post" enctype = "multipart/form data" <td> <input type = "text" name = "username"/> </td> </tr> <tr> <td> ملف التحميل: </td> <td> <input type = "file" name = "file"/> </td> </td> <tr> <td> الوصف: </td> <td> name = "description"> </textarea> </td> </tr> <tr> <td> <td> <type type = "إرسال" value = "upload start"/> </td> </tr> </table> </pump> <viv> $ {msg} </div> </body> </html> servlet
استيراد java.io.ioException ؛ استيراد javax.servlet.servletexception ؛ استيراد javax.servlet.http.httpservlet ؛ استيراد javax.servlet.http.httpservletrequest ؛ استيراد javax.servlet.http.httpservletresponse ؛ استيراد org.apache.commons.fileupload.fileuploadbase.filesizeLimitexceedEdException ؛ استيراد org.apache.commons.fileupload.fileuploadbase.sizeLimitexceedEdException ؛ استيراد org.apache.commons.fileupload.servlet.servletfileupload ؛ استيراد com.itheima.domain.upfile ؛ استيراد com.itheima.exception.myexception ؛ استيراد com.itheima.service.upfileservice ؛ استيراد com.itheima.service.impl.upfileserviceimpl ؛ استيراد com.itheima.untils.webuntil ؛ يمتد فئة exploadFileServlet العامة httpservlet {public void dogge (httpservletrequest request ، httpservletresponse) يلقي servletexception ، ioException {dopost (request ، response) ؛ } rework public void dopost (httpservletrequest request ، httpservletresponse) يلقي servletexception ، ioException {// just ما إذا كان النموذج يتكون من أجزاء متعددة إذا (! request.getRequestDispatcher ("/upload.jsp"). إلى الأمام (طلب ، استجابة) ؛ يعود ؛ } // إذا كانت عبارة عن جزء متعدد الأجزاء ، احصل على كائن تحميل الملف ، والذي يحتوي على جميع المعلومات التي تم تحميلها ، جرب {upfile upfile = webuntil.upload (request) ؛ upfileservice upfileservice = جديد upfileserviceimpl () ؛ العلم المنطقي = upfileservice.add (upfile) ؛ if (flag) {request.setAttribute ("msg" ، "تحميل ناجح") ؛ request.getRequestDispatcher ("/upload.jsp"). إلى الأمام (طلب ، استجابة) ؛ يعود ؛ } آخر {request.setattribute ("msg" ، "فشل التحميل ، يرجى المحاولة مرة أخرى") ؛ request.getRequestDispatcher ("/upload.jsp"). إلى الأمام (طلب ، استجابة) ؛ يعود ؛ }} catch (filesizeLiMitexceedEdException e) {E.PrintStackTrace () ؛ request.setattribute ("MSG" ، "حجم الملف الفردي ، يتجاوز الحد الأقصى") ؛ request.getRequestDispatcher ("/upload.jsp"). إلى الأمام (طلب ، استجابة) ؛ يعود ؛ } catch (sizelimitexactionedException e) {e.printStackTrace () ؛ request.setattribute ("MSG" ، "حجم الملف الكلي ، يتجاوز الحد الأقصى") ؛ request.getRequestDispatcher ("/upload.jsp"). إلى الأمام (طلب ، استجابة) ؛ يعود ؛ }}}أدوات
استيراد java.io.file ؛ استيراد java.io.filenotfoundException ؛ استيراد java.io.fileOutputStream ؛ استيراد java.io.ioException ؛ استيراد java.io.inputstream ؛ استيراد java.io.outputStream ؛ استيراد java.io.usupportedencodingexception ؛ استيراد java.util.arraylist ؛ استيراد java.util.list ؛ استيراد java.util.uuid ؛ استيراد javax.servlet.http.httpservletrequest ؛ استيراد org.apache.commons.fileupload.fileItem ؛ استيراد org.apache.commons.fileupload.fileuploadbase ؛ استيراد org.apache.commons.fileupload.fileuploadbase.filesizeLimitexceedEdException ؛ استيراد org.apache.commons.fileupload.fileuploadexception ؛ استيراد org.apache.commons.fileupload.ProgressListener ؛ استيراد org.apache.commons.fileupload.disk.diskfileItemFactory ؛ استيراد org.apache.commons.fileupload.servlet.servletfileupload ؛ استيراد com.itheima.domain.upfile ؛ استيراد com.itheima.exception.myexception ؛ / ** * فئة أداة تحميل الملف * describe todo * */ public class webuntil {/ ** * طريقة تحميل الملف * request request pass pass the request in reverurn repring a upfile consure * atherseizeLimitexceptionedException filesizeLiMiteScentedException ، sizelimitexacteedException {upfile upfile = new upfile () ؛ ArrayList <string> fileList = initList () ؛ جرب {// الحصول على كائن ملف القرص DiskfileItemFactory Factory = new DiskfileItemFactory () ؛ String tmp = request.getSession (). getServletContext (). getRealPath ("/tmp") ؛ System.out.println (TMP) ؛ // تهيئة setFactory المصنع (المصنع ، TMP) ؛ // احصل على تحميل الملف servletfileupload تحميل = جديد servletfileupload (المصنع) ؛ // تهيئة setupload parser (التحميل) ؛ // الحصول على قائمة الملفات <IpiTIm> list = upload.parserequest (request) ؛ // Travel for (fileItem عناصر: قائمة) {// upply ما إذا كان كائن نموذج عادي if (items.isformfield ()) {// احصل على اسم سلسلة التحميل FieldName = itemS.GetFieldName () ؛ // value سلسلة fieldvalue = items.getString ("UTF-8") ؛ // ugge if ("username" .equals (fieldName)) {// set upfile.setUserName (fieldValue) ؛ } آخر إذا ("الوصف" .equals (fieldName)) {// قم بتعيين السمة upfile.setDescription (FieldValue) ؛ }} else {// هي الملف جاهزًا لتحميل // الحصول على اسم ملف اسم الملف = itemS.GetName () ؛ // التعامل مع الاختلافات في أسماء الملفات التي تم الحصول عليها بسبب متصفحات مختلفة int index = filename.lastindexof ("//") ؛ if (index! =-1) {filename = filename.subString (index+1) ؛ } // إنشاء أسماء ملفات عشوائية uuidname = generateFilename (اسم الملف) ؛ // احصل على سلسلة مسار الملف المحملة SavePath = request.getSession (). getServletContext (). // الحصول على دفق الإدخال في كائن الطلب inputStream في = items.getInputStream () ؛ // كسر الملف وتخزينه في مسارات مختلفة ، ابحث عن path savepath = enderandOmdir (SavePath ، UuidName) ؛ // انسخ ملف uploadFile (في ، SavePath ، UuidName) ؛ string id = uuid.randomuuid (). toString () ؛ upfile.setid (id) ؛ upfile.setsavepath (SavePath) ؛ upfile.setuuidName (uuidname) ؛ upfile.setFilename (اسم الملف) ؛ // clear cache items.delete () ؛ }}} catch (fileuploadbase.filesizeLimitexceedEdException e) {// top a revision throw e ؛ } catch (fileuploadbase.sizeLimitexceedEdException e) {// استثناء رميات e ؛ } catch (fileuploadexception e) {eprintStackTrace () ؛ } catch (UnsupportedEncodingException e) {E.PrintStackTrace () ؛ } catch (ioException e) {E.PrintStackTrace () ؛ } catch (استثناء e) {E.PrintStackTrace () ؛ } العودة upfile ؛ } / *** تهيئة قائمة الملفات* return* / private static arraylist <string> initList () {ArrayList <string> list = new ArrayList <String> () ؛ list.add (". JPG") ؛ list.add (". rar") ؛ list.add (". txt") ؛ list.add (". png") ؛ قائمة العودة } /*** نسخ ملف* دفق الإدخال في param في العناصر* param savepath save path* param uuidname name* /private static void uploadfile (inputStream in ، string savepath ، string uuidname) {// get file file file = new file (savepath ، uuidname) ؛ OutputStream Out = null ؛ حاول {int len = 0 ؛ Byte [] buf = new byte [1024] ؛ // الحصول على دفق الإخراج Out = fileOutputStream جديد (ملف) ؛ بينما ((len = in.read (buf))! =-1) {out.write (buf ، 0 ، len) ؛ }} catch (fileNotfoundException e) {e.printStackTrace () ؛ } catch (ioException e) {E.PrintStackTrace () ؛ } أخيرًا {try {in.close () ؛ } catch (ioException e) {E.PrintStackTrace () ؛ } حاول {out.close () ؛ } catch (ioException e) {E.PrintStackTrace () ؛ }}} /*** إنشاء مسار تخزين عشوائي* param savepath save path* param uuidname اسم uuid الذي تم إنشاؤه* @return* استخدم hashcode لإكمال* /private static string generaterandomdir (string savepath ، string uuidname) {// تحويل system.println ( system.out.println ("uuidname"+uuidname) ؛ int hashcode = uuidname.hashCode () ؛ // Container StringBuilder SB = New StringBuilder () ؛ بينما (hashcode> 0) {// int 15 int tmp = hashcode & 0xf ؛ sb.append ("/") ؛ SB.Append (TMP+"") ؛ hashcode = hashcode >> 4 ؛ } // تقسيم مسار سلسلة مسار جديد = SavePath+SB.ToString () ؛ system.out.println ("path"+path) ؛ ملف الملف = ملف جديد (مسار) ؛ // ugge ما إذا كان المسار موجودًا إذا (! file.exists ()) {// إنشاء file.mkdirs () ؛ } // إرجاع مسار إرجاع مسار حفظ ؛ } / *** قم بإنشاء اسم ملف جديد* param uuidname اسم معرف عشوائي* param filename الاسم الأصلي* regurn* / private static string generatefilename (filename string) {string uuidname = uuid.randomuid (). toString () ؛ إرجاع uuidname.replace ("-" ، "") .ToString ()+"_"+filename ؛ } / *** محلل التهيئة* param upload* / private static void setupload (servletfileUpload upload) {// set charse formpload.setheaderencoding ("utf-8") ؛ // تعيين حجم الملف epload.setfilesizemax (1024*1024*20) ؛ // تعيين إجمالي حجم الملف. setsizemax (1024*1024*50) ؛ // قم بتعيين تقدم مستمع upload.setProgressRistener (New ProgressListener () {تحديث public void (pbytesread طويل ، طول pcontentLength ، int int) {system.out.println ("read: *param tmp directory*/ private static void setFactory (diskfileitemfactory factory ، قم بتنزيل ملفين
servlet
يمتد DownupFileServlet الفئة العامة httpservlet {public void doget (httpservletrequest request ، httpservletresponse) يلقي servletexception ، ioException {dopost (request ، repress) ؛ } public void dopost (httpservletRequest request ، httpservletresponse) يلقي servletexception ، ioException {// الحصول على معرف المعرف = request.getParameter ("id") ؛ // واجهة طبقة العمل upfileservice upfileservice = جديد upfileserviceimpl () ؛ // ابحث عن هذا الكائن بناءً على upfile upfile upfile = upfileservice.findupfilebyid (id) ؛ if (upfile == null) {return ؛ } // احصل على الاسم الحقيقي لـ File String Filename = upfile.getFilename () ؛ // إذا كان هناك صيني في اسم الملف ، فيجب نقله ، وإلا فلن يكون هناك اسم ملف اسم الملف = urlencoder.encode (اسم الملف ، "UTF-8") ؛ // تغيير الاسم سلسلة uuidname = upfile.getUuidName () ؛ // Save Path String SavePath = upfile.getSavePath () ؛ ملف الملف = ملف جديد (SavePath ، UuidName) ؛ // حدد ما إذا كان الملف موجودًا إذا انتهت صلاحية (!! request.getRequestDispatcher ("/index"). إلى الأمام (طلب ، استجابة) ؛ يعود؛ } // قم بتعيين ملف معلومات Download Deptans Response. // استخدم دفق IO لإخراج inputStream في = FileInputStream جديد (ملف) ؛ servleToutPutStream out = response.getOutputStream () ؛ int len = 0 ؛ Byte [] buf = new byte [1024] ؛ بينما ((len = in.read (buf))! =-1) {out.write (buf ، 0 ، len) ؛ } in.close () ؛ }}قاعدة البيانات
إنشاء قاعدة البيانات expload_download_exercise ؛ استخدم expload_download_exercise ؛ إنشاء الجدول Upfiles (ID varchar (100) ، // استخدم UUID لإنشاء UUIDNAME varchar (255) ، // UUID بالإضافة إلى اسم الملف الأصلي اسم FILENARD VARCHAR (100) ، // real file name savepath varchar (10)
ما سبق هو المحتوى ذي الصلة لجافا باستخدام commos-fileupload لتحقيق تحميل الملفات وتنزيلها ، وآمل أن يكون مفيدًا للجميع.