Saya tidak ada hubungannya, jadi saya menulis servlet untuk mengimplementasikan fungsi unggahan dan unduhan. Setelah memulai layanan, Anda bisa menjadi server file kecil di LAN.
1. Persiapan
Unduh dua paket stoples:
Commons-Fileupload-1.3.1.jar
commons-io-2.2.jar
2. Buat proyek web
Proyek saya disebut: Z-Upload
3. Konfigurasikan 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/xmlns =" http://java.com/xmlns = "http://java.com/xmlns = XSI: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/we-pappe." "" "" "" "" "" "" "" "" "" <display-name>z-upload</display-name> <servlet> <servlet-name>UploadService</servlet-name> <servlet-class>com.syz.servlet.UploadService</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadService</servlet-name> <url-pattern>/*</url-pattern> </servlet-Mapping> </web-app>
Dari konfigurasi di atas, kita dapat melihat bahwa kelas servlet saya adalah UploadService, dan URL yang cocok adalah /*, yang berarti mencocokkan semua URL akses.
4. Tulis kelas servlet
Paket com.syz.servlet; impor java.io.file; impor java.io.fileInputStream; impor java.io.fileoutputStream; import java.io.ioException; impor java.io.inputStream; impor java.io.outputStream; impor java.io.pr bijiarter; java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletcontext; import javax.servlet.servletException; import javax.servlet.htp.httpservlet; impor javax.servlet javax.servlet.http.httpservletResponse; import org.apache.commons.fileupload.fileitem; Impor org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileuploaderenererenererenererenererenererenererenererenererenererenererenererenererenererenerereneren; org.apache.commons.fileupload.disk.diskfileItemFactory; import org.apache.commons.fileupload.servlet.servletfileUpload; kelas publik unggahan servet memperluas httpservlet {public static final string list = "/list"; Formulir String Akhir Statis Publik = "/formulir"; handle string final static public = "/handle"; download string akhir public static = "/download"; string final final statis public delete = "/delete"; string final statis public unggah_dir = "/unggah"; SerialVersionuid Long Final Pribadi = 2170797039752860765L; public void execute (httpservletRequest req, httpservletResponse resp) melempar servletException, ioException {system.out.println ("Execute ..."); System.out.println ("------------ Mulai ---------------"); req.setcharacterencoding ("UTF-8"); Host string = req.getRemotehost (); System.out.println ("Host:" + Host); String uri = req.getRequesturi (); System.out.println ("URI:" + URI); ServletContext servletContext = this.getSerVletConfig () .getSerVletContext (); // Jalur dasar untuk mengunggah file string basePath = servletContext.getRealPath (unggah_dir); // Context Path String ContextPath = ServletContext.GetContextPath (); System.out.println ("ContextPath:" + ContextPath); // path setelah mencegat context string action = uri.substring (contextPath.length ()); System.out.println ("Action:" + Action); // pemrosesan yang berbeda dilakukan sesuai dengan tindakan yang berbeda jika (action.equals (form)) {form (contextPath, resp); } lain jika (action.equals (handle)) {boolean ismultipart = servletfileupload.ismultipartcontent (req); System.out.println ("IsMultipart:" + IsMultipart); if (! isMultipart) {return; } DiskFileItemFactory factory = DiskFileItemFactory baru (); File repository = (file) servletContext .getAttribute (servletcontext.tempdir); System.out.println ("Repositori:" + Repository.getAbsolutePath ()); System.out.println ("Basepath:" + Basepath); factory.setsizethreshold (1024 * 100); factory.setrepository (repositori); SERVLETFILEUPLOAD UEDLOAD = SERVLETFILEUPLOAD baru (pabrik); // Buat pendengar ProgressListener progressListener = new ProgressListener () {public void update (long pbytesread, long pcontentLength, int pitems) {System.out.println ("Ukuran file saat ini:" + pContentLength + "/t sudah diproses:" + pbytesread); }}; unggah.setProgressListener (ProgressListener); Daftar <FILEITEM> item = NULL; coba {item = unggah.parsequest (req); System.out.println ("Ukuran Item:" + Items.Size ()); Iterator <FILEItEM> item = items.iterator (); while (ite.hasnext ()) {fileItem item = item.next (); if (item.isFormField ()) {// menangani formfield} else {// menangani 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 (); ukuran panjanginbytes = item.getSize (); System.out.println (fieldName + "/t" + fileName + "/t" + contentType + "/t" + isInmemory + "/t" + sizeinbytes); File File = File Baru (Basepath + "/" + FileName + "_" + getuffix ()); // item.write (file); InputStream in = item.getInputStream (); OutputStream out = FileOutputStream baru (file); byte [] b = byte baru [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); melampirkan(); out.close (); }} // Redirect ke halaman daftar file setelah memproses string href1 = contextPath + daftar; resp.sendredirect (href1); } catch (FileuploAdException e) {E.PrintStackTrace (); } catch (Exception e) {E.PrintStackTrace (); }} lain 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; } File file = file baru (Basepath); File [] list = file.listFiles (); int len = list.length; bendera boolean = false; untuk (int i = 0; i <len; i ++) {file f = daftar [i]; String fn = f.getName (); if (f.isfile () && fn.LastIndexof ("_")> -1) {string fid = fn.substring (fn.LastIndexof ("_"))); if (id.equals (fid)) {download (f, resp); bendera = true; merusak; }}} if (! flag) {notfound (contextPath, resp); }} lain jika (action.equals (delete)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } File file = file baru (Basepath); File [] list = file.listFiles (); int len = list.length; bendera boolean = false; untuk (int i = 0; i <len; i ++) {file f = daftar [i]; String fn = f.getName (); if (f.isfile () && fn.LastIndexof ("_")> -1) {string fid = fn.substring (fn.LastIndexof ("_"))); if (id.equals (fid)) {f.delete (); bendera = true; merusak; }}} if (flag) {// redirect ke halaman daftar file setelah memproses string href1 = contextPath + daftar; resp.sendredirect (href1); } else {notfound (ContextPath, resp); }} else {show404 (ContextPath, resp); } System.out.println ("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Printwriter = resp.getWriter (); Untuk kembali ke daftar file </b> "); out.write (" </body> "); out.write (" </html> "); out.close ();} bentuk kekosongan pribadi (string contextPath, httpservletResponse resp) lemparan ioException {resp.setcontentType (" TEKS/TEKS/TEKSPET; HTM; UTFICSCEPON; resp.getWriter (); out.write ("<head> <title> form </iteme> </head>"); out.write ("<body>"); out.write ("<b> <a href = '" + href1 + "'> klik </a> Untuk kembali ke daftar file </b>"); out.write ("<bentuk action = 'handle' method = 'post' enctype = 'multipart/form-data' style = 'margin-top: 20px;'>"); out.write ("<input name = 'file' type = 'file'/> <br>"); out.write ("<input type = 'kirim' nilai = 'unggah'/> <br>"); out.write ("</form>"); out.write ("</body>"); out.write ("</html>"); out.close (); } private void notfound (String ContextPath, httpservletResponse resp) melempar ioException {resp.setContentType ("Text/html; charset = utf-8"); Printwriter out = resp.getWriter (); String href1 = contextPath + daftar; out.write ("<html> <body> <b> Operasi gagal! File tidak ada atau file telah dihapus! <a href = '" + href1 + "'> klik </a> untuk kembali ke daftar file </b> </body> </html>"); out.close (); } unduhan private void (file f, httpservletResponse resp) melempar ioException {string fn = f.getName (); String filename = fn.substring (0, fn.LastIndexof ("_")); System.out.println ("nama file:" + nama file); resp.reset (); resp.setContentType ("Aplikasi/Octet-Stream"); String encodingFileName = string baru (filename.getbytes ("gbk"), "iso8859-1"); System.out.println ("encodingFileName:" + encodingFileName); resp.setheader ("konten-disposisi", "lampiran; fileName =" + encodingFileName); InputStream in = new FileInputStream (f); OutputStream out = resp.getoutputStream (); byte [] b = byte baru [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); melampirkan(); out.close (); } private void list (String ContextPath, String Basepath, httpservletResponse resp) melempar ioException {string href_u = contextPath + form; resp.setContentType ("Teks/html; charset = utf-8"); Printwriter out = resp.getWriter (); out.write ("<html>"); out.write ("<head> <title> Daftar </iteme> </head>"); out.write ("<body>"); out.write ("<b> Saya ingin <a href = '" + href_u + "'> Unggah </a> </b> <br>"); out.write ("<tabel border = '1' style = 'border-collapse: collapse; lebar: 100%; margin-top: 20px;'>"); out.write ("<Thead>"); out.write ("<tr>"); out.write ("<th> nomor seri </th> <t th> nama file </th> <th> operasi </t>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); File file = file baru (Basepath); File [] list = file.listFiles (); System.out .println ("Basepath:" + Basepath + "/Tlist.Size:" + list.length); int len = list.length; int no = 1; untuk (int i = 0; i <len; i ++) {file f = daftar [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 + hapus + "? Id =" + id; StringBuilder SB = StringBuilder baru (); SB.Append ("<tr>"); SB.Append ("<td>"); SB.Append (no ++); SB.Append ("</td>"); SB.Append ("<td>"); SB.Append (nama file); SB.Append ("</td>"); SB.Append ("<td>"); SB.Append ("<a href = '"); SB.Append (HREF1); SB.Append ("'> Unduh </a> <a href ='"); SB.Append (href2); SB.Append ("'OnClick =' Return Confirm (/" Apakah Anda yakin ingin menghapusnya?/"); '> hapus </a>"); SB.Append ("</td>"); SB.Append ("</tr>"); out.write (sb.tostring ()); }} out.write ("</tbody>"); out.write ("</able>"); out.write ("</body>"); out.write ("</html>"); out.close (); } public void doGet (httpservletRequest req, httpservletResponse resp) melempar servletException, ioException {system.out.println ("doGet ..."); eksekusi (req, resp); } public void dopost (httpservletRequest req, httpservletResponse resp) melempar servletException, ioException {system.out.println ("dopost ..."); eksekusi (req, resp); } private string getSuffix () {date date = new date (); SimpleDateFormat SDF = new SimpleDateFormat ("yyyymmddhhmmssssss"); String suffix = sdf.format (tanggal); Kembalikan akhiran; }}Bahkan, kelas UploadService dapat secara langsung mengimplementasikan metode layanan tanpa mengimplementasikan metode doGet dan dopost.
Saya tidak ingin menjelaskan apa pun tentang servlets di atas, cukup baca kodenya sendiri.
5. Diagram reproduksi
1. Diagram Struktur Proyek
Halaman 2.404
/* akan mencocokkan semua karakter nol, sehingga jalur dalam gambar akan cocok, yang muncul di tempat lain di IF Judgment in UneadService, karena aksi saat ini adalah karakter nol.
3. Halaman Daftar File
4. Halaman Formulir Unggah
5. Unduh
6. hapus
7. File tidak dapat ditemukan. Jika file tidak ada lagi di server saat Anda mengklik Hapus, maka Anda akan memasukkan halaman ini.
8. Proyek Kode Sumber Kemasan dan Paket Perang
Di antara mereka, Z-Upload adalah Proyek Kode Sumber Eclipse, dan Z-Upload.war adalah paket Perang Siap
Hanya ada dua paket toples di seluruh proyek, satu web.xml dan satu kelas servlet. Anda dapat menyalinnya dari artikel dan mengujinya. Jika Anda malas, Anda dapat mengunduhnya.
http://download.csdn.net/detail/yunsyz/9569680, pengingat khusus, unduh untuk 1 poin.
Di atas adalah semua konten artikel ini. Saya harap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.