Загрузить, загружать и управлять технологией функциональных файлов: 1. Используйте XML в качестве информации о хранении базы данных (DOM4J, XPATH)
2. Загрузить и загружать формы Java
3. Разрушение каталога файлов (каталог хэша - это метод оптимизации производительности хранилища файлов)
Нужен пакет JAR:
Commons-FileUpload-1.2.2.jar, Commons-IO-2.1.jar, Dom4j-1.6.1.jar и Jaxen-1.1-beta-6.jar
----------------------------------------------------------------------------------
Напишите index.jsp в первую очередь
<%@ page language = "java" import = "java.util.*" pageencoding = "UTF-8"%> <! Doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <Head> </html </title> </Head> <Hatml> <Head> </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </h1 </hml> <html> <hteml> </h1 </h1 </h1 </h11 href = "jsps/upload.jsp"> загрузить альбом </a> <a href = "servlets/showservlet"> альбом обновления </a> </body> </html>
upload.jsp - это страница загрузки, размещенная в каталоге JSPS
<%@ page language = "java" import = "java.util.*" pageencoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 transitional // en"> <html> <Head> </hade> <hody> <h1> </h1> action = "<%= request.getContextPath ()%>/servlets/uploadservlet" method = "post" ectype = "multipart/form-data"> файл: <input type = "file" name = "file1"/> <br/> Описание: <input = "text" name = "desc"/> <br/> <input = "Vade =" upload "/> </> <bry> </> <br/> <input =" value = "/> </> </> <br/> <input =" "/> </> </> <br/> <input =" " </body> </html>
Поместите Photo.xml в каталог SRC
<? xml version = "1.0" Encoding = "UTF-8"?> <Фото> </photos>
Write value photomodel photomodel
пакет cn.hncu.demain; открытый класс Photomodel {private String Id; частная строка realName; частная строка ext; частная строка Dir; частная строка DateTime; частная строка IP; частная строка Desc; public String getId () {return id; } public void setId (String id) {this.id = id; } public String getRealName () {return realName; } public void setRealName (String RealName) {this.RealName = realName; } public String getExt () {return Ext; } public void setext (string ext) {this.ext = ext; } public String getDir () {return dir; } public void setDir (String dir) {this.dir = dir; } public String getDateTime () {return dateTime; } public void setDateTime (String DateTime) {this.DateTime = dateTime; } public String getip () {return ip; } public void setip (String ip) {this.ip = ip; } public String getDesc () {return desc; } public void setDesc (String desc) {this.desc = desc; } @Override public String toString () {return "PhotoModel [id =" + id + ", realName =" + realName + ", ext =" + ext + ", dir =" + dir + ", dateTime =" + dateTime + ", ip =" + ip + ", desc = desc +"] "; }} Есть два типа инструментов письма:
Myutil (форматирование даты, код разбития каталогов, случайный идентификационный код)
пакет cn.hncu.utils; import java.text.simpledateformat; импорт java.util.date; импорт java.util.uuid; открытый класс myutils {private myutils () {} Частный статический формат Simpledateformat = new Simpledateformat («Yyyy Year Mom Mom DD DD DD HH: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: S: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM: MM. public Static String getCurrentDateTime () {return format.format (new Date ()); } public static String getUuid () {uuid uuid = uuid.randomuuid (); String id = uuid.toString (). RayAlceall ("-", ""); вернуть идентификатор; } public Static String getDir (String uuid) {string dir1 = integer.tohexstring (uuid.hashcode () & 0xf); String dir2 = integer.tohexstring ((uuid.hashcode () & 0xf0) >> 4); вернуть dir1+"/"+dir2; }}Dom4jJfactory (связанные операции DOM4J, получить объект документа, сохранение операции)
Пакет cn.hncu.utils; import java.io.file; import java.io.fileinputstream; импорт java.io.filenotfoundexception; импорт java.io.fileoutputstream; импорт java.io.unsupportedExexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexex org.dom4j.io.outputformat; import org.dom4j.io.saxReader; импорт org.dom4j.io.xmlwriter; public class dom4jfactory {частный статический документ dom = null; частный статический путь строки; static {try {saxreader sax = new Saxreader (); // Узнайте, как загрузить путь ресурса под сервером (потому что наши ресурсы были опубликованы из MyeClipse на сервер Tomcat, поэтому он отличается от исходного проекта Pure Java) // Используйте текущий класс, чтобы найти его загрузчик класса, а затем используйте загрузчик класса, чтобы получить путь к ресурсу. dom = sax.read (new FileInputStream (path)); } catch (Exception e) {бросить новое runtimeexception (e.getmessage (), e); }} public Static Document getDom () {return dom; } public static boolean save () {try {outputformat format = new outputFormat (); format.setencoding ("UTF-8"); Xmlwriter w = new XmlWriter (new FileOutputStream (новый файл (path)), format); W.Write (dom); w.close (); вернуть истину; } catch (Exception e) {return false; }}}Напишите Photodao из нижнего слоя
Пакет cn.hncu.dao; import java.util.arraylist; import java.util.iterator; import java.util.list; import org.dom4j.document; import org.dom4j.element; импорт cn.hncu.demain.photomodel; import cn.hncu.m.dom. Boolean Add (PhotoDel Photo) {Document dom = dom4jfactory.getdom (); Элемент root = dom.getRootElement (); Element ephoto = root.addelement ("photo"); ephoto.addattribute ("id", photo.getid ()); ephoto.addattribute ("realName", photo.getRealName ()); ephoto.addattribute ("dir", photo.getdir ()); ephoto.addattribute ("ip", photo.getip ()); ephoto.addattribute ("dateTime", photo.getDateTime ()); ephoto.addattribute ("ext", photo.getext ()); ephoto.addelement ("desc"). setText (photo.getDesc ()); Boolean boo = dom4jfactory.save (); вернуть бу; } // Просмотр публичного списка <photoModel> getAll () {document dom = dom4jfactory.getdom (); Список <photomodel> list = new Arraylist <Photomodel> (); Элемент root = dom.getRootElement (); Итератор <element> it = root.elementiterator (); while (it.hasnext ()) {photoModel photo = new PhotoModel (); Элемент e = it.next (); photo.setid (e.attributevalue ("id")); photo.setDateTime (e.attributeValue ("dateTime")); photo.setdir (e.attributevalue ("dir")); photo.setext (e.attributevalue ("ext")); photo.setip (e.attributevalue ("ip")); photo.setRealName (e.attributeValue ("realName")); photo.setdesc (elementext ("desc")); list.add (фото); } return List; } public photomodel etsinglebyId (String Id) {Document dom = dom4Jfactory.getDom (); Список <photomodel> list = getall (); для (фотомодель фото: список) {if (photo.getid (). equals (id)) {return photo; }} return null; } public boolean del (String id) {document dom = dom4jfactory.getdom (); Элемент e = (элемент) dom.selectsinglenode ("// photo [@id = '"+id.trim ()+"']"); вернуть e.getParent (). Удалить (e); }} Напишите четыре сервлета в конце
Загрузка Servlet Загрузить код сервлета
Пакет cn.hncu.servlets; import java.io.file; import java.io.ioexception; импорт java.io.inputstream; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; import.serv.http.httplet. javax.servlet.http.httpservlectrequest; import javax.servlet.http.httpservletresponse; импорт org.apache.commons.fileupload.fileitem; импорт org.apache.commons.fileupload.fileuadexception; org.apache.commons.fileupload.disk.diskFileItemFactory; импорт org.apache.commons.fileupload.servlet.servletfileupload; импорт org.apache.commons.io.fileutils; импорт. cn.hncu.utils.myutils; открытый класс uploadservlet расширяет httpservlet {public void doget (httpservletrequest, httpservletresponse response) vestletexception, ioexception {response.setContentType ("text/html; charsexception, ioException {respons. Printwriter Out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transitional // en/">"); out.println ("<html>"); out.println ("<head> <Title> a Servlet </title> </head>"); out.println ("<body>"); out.println («Загрузка не поддерживается!»); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); } public void dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {response.setContentType ("text/html; charset = utf-8"); Printwriter Out = response.getWriter (); String path = request.getServletContext (). GetRealPath ("/photos"); DiskFileItemfactory Factory = new DiskFileItemFactory (); factory.setrepository (новый файл ("g:/a")); ServletFileUpload upload = new ServletFileUpload (Factory); upload.setsizemax (1024*1024*10); // максимум 10 м opload.setheaderencoding ("utf-8"); // Использование для установки кодирования имени файла, эквивалентного: request.setcharacterencoding ("utf-8"); Fileitem fi = null; try {list <fieleItem> list = opload.parserequest (request); Photomodel photo = new PhotoModel (); // Инкапсуляция данных --- 7 Атрибуты требуются логические BOO = false; InputStream in = null; для (fileitem fi2: list) {fi = fi2; if (fi.isformfield ()) {string desc = fi.getString ("utf-8"); photo.setDesc (desc); // desc} else {in = fi.getInputStream (); String realName = fi.getName (); if (realName == null || realName.trim (). equals ("")) {out.print ("Нет файла не выбрана!"); возвращаться; } if (realName.indexof ("//")! =-1) {realName = realName.substring (realName.lastIndexof ("//")+1); } photo.setRealName (realName); // raue file name string = realName.substring (realName.lastIndexof (".")); photo.setext (ext); // 3 photo.setDateTime (myutils.getCurrentDateTime ()); // 4 photo.setid (myutils.getuuid ()); // 5 photo.setdir (myutils.getdir (photo.getid ()); // 6 photo.setip (requare.getRemoteddr ();//// sphote. База данных PhotoDao dao = new PhotoDao (); boo = dao.add (фото); // Если информация о фотографии выше успешно сохраняется, вы начнете получать файл изображения и сохранить его на жесткий диск Server if (boo) {System.out.println (dao); path = path+"/"+photo.getDir (); Файл dir = new File (path); if (! dir.exists ()) {dir.mkdir (); } String filename = path+"/"+photo.getId ()+photo.getext (); Fileutils.copyinputstreamtofile (in, новый файл (имя файла)); String strPath = request.getContextPath ()+"/servlets/showservlet"; out.print ("Загружено успешно! <a href = '"+strpath+"'> обзор альбома </a>"); } else {out.print ("upload не удалась!"); }} catch (fileuploadexception e) {throw new Runtimeexception ("upload не удалась!"); ", e);} наконец {if (fi! = null) {fi.delete ();}} out.flush (); out.close ();}}Showervlet Сервлетовая сторона просмотра альбомов
Пакет cn.hncu.servlets; импорт java.io.ioexception; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; импорт javax.servlet.http.httpservlet; import javax.servlet.http.httreplectrevlet; import javax.servlet.http.httrep.httpservlet; import javax.servlet.htt javax.servlet.http.httpservletresponse; import cn.hncu.dao.photodao; import cn.hncu.demain.photomodel; открытый класс показывает httpservlet {ioexception, если ошибка возникает общедоступный дог. ServletException, ioException {DoPost (запрос, ответ); } public void dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {response.setContentType ("text/html; charset = utf-8"); request.setcharacterencoding ("UTF-8"); Printwriter Out = response.getWriter (); out.println ("<! Doctype html public/"-// w3c // dtd html 4.01 transitional // en/">"); out.println ("<html>"); out.println ("<head> <Title> a Servlet </title> </head>"); out.println ("<body>"); String table = "<table border = '1' width = '100%'>"+ "<tr> <th> имя файла </th> <t.> загрузить ip </th> <Th> время загрузки </th> <T.> Image </th> <Th> out.print (таблица); Photodao dao = new Photodao (); Список <photomodel> list = dao.getall (); для (Photomodel P: List) {out.print ("<tr>"); out.println ("<td>"+p.getRealname ()+"</td>"); out.println ("<td>"+p.getip ()+"</td>"); out.println ("<td>"+p.getDateTime ()+"</td>"); // Выходная картина String Path = request.getContextPath ()+"/photos/"+p.getDir ()+"/"+p.getid ()+p.getext (); out.println ("<td> <a href = '"+path+"'> <img src = '"+path+"' width = '200' height = '200'> </img> </a> </td>"); String op = "<a href = '"+request.getContextPath ()+"/servlets/delservlet? ID ="+p.getid ()+"'> delete </a>"; out.println ("<td>"+p.getdesc ()+"</td>"); op+= "<a href = '"+request.getContextPath ()+"/servlets/downservlet? id ="+p.getid ()+"'> скачать </a>"; out.println ("<td>"+op+"</td>"); out.print ("</tr>"); } out.println ("</table>"); out.println ("</body>"); out.println ("</html>"); out.flush (); out.close (); }}Код сервера загружен Downservlet
Пакет cn.hncu.servlets; import java.io.fileinputstream; импорт java.io.fileoutputstream; import java.io.ioexception; импорт java.io.inputstream; import java.io.OutputStream; import java.io.printwriter; importexerex.sersex.sersex.sersersex.servex.servex.servex.Servex.Servex. javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletrespons Httpservlet {public void doget (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {dopost (запрос, ответ); } public void dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {string id = request.getParameter ("id"); response.setContentType ("Приложение/Force-Download"); Photomodel p = new Photodao (). Etsinglybyid (id); if (p! = null) {string realName = p.getRealName (); realName = new String (realName.getBytes ("iso8859-1"), "UTF-8"); response.setheader ("Distosition", "ATTHAMENT; FILENAME =/" "+realName+"/""); String relpath = getServletContext (). GetRealPath ("/photos/"+p.getDir ()+"/"+p.getid ()+p.getext ()); InputStream in = new FileInputStream (RelPath); OutputStream out = response.getOutputStream (); System.out.println (Relpath); byte buf [] = новый байт [1024]; int len = 0; while ((len = in.read (buf))! =-1) {out.write (buf, 0, len); } out.close (); } else {response.setContentType ("text/html; charset = utf-8"); response.getWriter (). println («Этот файл был удален!»); }}}Delservlet Delete Server
Пакет cn.hncu.servlets; import java.io.file; импорт java.io.fileinputstream; импорт java.io.ioexception; импорт java.io.inputstream; импорт java.io.outputstream; import java.io.printwriter; import javax.servlet.servletexcepte; javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletrespons Httpservlet {public void doget (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {dopost (запрос, ответ); } public void Dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {request.setcharacterencoding ("utf-8"); response.setContentType ("text/html; charset = utf-8"); Printwriter Out = response.getWriter (); String id = request.getParameter ("id"); Photomodel p = new Photodao (). Etsinglybyid (id); if (p! = null) {if (! p.getip (). Equals (request.getRemoteaddr ())) {out.println («У вас нет разрешения на удаление его!»); возвращаться; } // ※※※※ Следующие части добавляются в следующий класс !!! // 1delete информация в базе данных PhotoDao dao = new PhotoDao (); Boolean boo = dao.del (id); // 2delete файл на сервере жесткий диск if (boo) {string filename = "photos/"+p.getdir ()+"/"+p.getid ()+p.getext (); String pathfilename = getServletContext (). GetRealPath (имя файла); Файл f = новый файл (pathfilename); if (f.exists ()) {f.delete (); } String strPath = request.getContextPath ()+"/servlets/showerervlet"; out.println ("Photo Delete успешно! <a href = '"+strpath+"'> обзор альбома </a>"); } else {out.println ("Фото удаление не удалось!"); }} else {response.setContentType ("text/html; charset = utf-8"); response.getWriter (). println («В этом файле не существует!»); }}}Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.