Мне нечего делать, поэтому я написал сервлет для реализации функции загрузки и загрузки. После запуска службы вы можете быть небольшим файловым сервером в локальной сети.
1. Подготовка
Скачать два пакета JAR:
Commons-FileUpload-1.3.1.jar
Commons-IO-2.2.jar
2. Создать веб -проект
Мой проект называется: z-upload
3. Настройка 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/xml/ns/javaee" 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.xsd" = "webapp" = "webapp" = "webapp_dapp_3_0.0. <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>
Из приведенной выше конфигурации мы видим, что мой класс сервлета является загруженным обслуживанием, а соответствующий URL -адрес составляет /*, что означает сопоставление всех URL -адресов доступа.
4. Напишите класс сервлета
Пакет com.syz.servlet; импорт java.io.file; импорт java.io.fileinputstream; импорт java.io.fileoutputstream; импорт java.io.ioexception; импорт java.io.inputstream; importa.io.OutputStream; импорт java.io.printwriter; импорт. java.util.date; import java.util.iterator; import java.util.list; import javax.servlet.servletcontext; import javax.servlet.servletexception; импорт javax.servlet.http.httpservlet; import javax.servlet.http.httperservelt; import javax.servlet.http.httperservlet; javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexcept org.apache.commons.fileupload.disk.diskFileItemFactory; import org.apache.commons.fileUpload.servlet.servletFileUpload; открытый класс uploadServlet Extends httpservlet {public Static final String List = "/list"; публичная статическая конечная строка форма = "/form"; Public Static Final String Handle = "/Harder"; public Static Final String скачать = "/скачать"; Public Static Final Final String delete = "/delete"; public Static Final String opload_dir = "/upload"; Частный статический последний длинный серийный режим = 2170797039752860765L; public void execute (httpservlectrequest req, httpservletresponse resp) бросает Servletexception, ioexception {System.out.println ("execute ..."); System.out.println ("------------ Begin ---------------"); req.setcharacterencoding ("UTF-8"); String host = req.getRemotehost (); System.out.println ("host:" + host); String uri = req.getRequesturi (); System.out.println ("uri:" + uri); ServletContext servletContext = this.getServletConfig () .getServletContext (); // Базовый путь для загрузки файла строки basePath = servletContext.getRealPath (upload_dir); // контекст пути строки contextPath = servletContext.getContextPath (); System.out.println ("contextPath:" + contextPath); // Путь после перехвата контекстной строки action = uri.substring (contextpath.length ()); System.out.println ("action:" + action); // Различная обработка выполняется в соответствии с различными действиями, если (action.equals (form)) {form (contextpath, sprop); } else if (action.equals (handle)) {boolean ismultipart = servletfileupload.ismultipartContent (req); System.out.println ("ismultipart:" + ismultipart); if (! ismultipart) {return; } Diskfileitemfactory factory = new DiskFileItemFactory (); File Repository = (file) ServletContext .getAttribute (servletContext.tempdir); System.out.println ("Repository:" + repository.getabsolutepath ()); System.out.println ("BasePath:" + BasePath); factory.setsizethershold (1024 * 100); factory.setRepository (Repository); ServletFileUpload upload = new ServletFileUpload (Factory); // Создать слушатель ProgressListener progressListener = new ProgressListener () {public void Update (long pbytesRead, long pcontentlength, int pitems) {System.out.println («Текущий размер файла:« + pcontentlength + »/t уже обработан:« + pbytesread); }}; upload.setProgressListener (ProgressListener); Список <FieleItem> items = null; try {items = upload.parserequest (req); System.out.println («Размер предметов:» + items.size ()); Iterator <fieTiTem> item = item.iterator (); while (ite.hasnext ()) {fileitem item = item.next (); if (item.isformfield ()) {// handle formfield} else {// обрабатывать строку файла fieldname = item.getfieldname (); String fileName = 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); File file = new File (basePath + "/" + filename + "_" + getSuffix ()); // item.write (file); InputStream in = item.getInputStream (); OutputStream out = new FileOutputStream (file); байт [] b = новый байт [1024]; int n = 0; while ((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) {e.printstacktrace (); } catch (Exception e) {e.printstackTrace (); }} else if (action.equals (list)) {list (contextpath, basepath, resp); } else if (action.equals (скачать)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } File file = new File (basePath); File [] list = file.listfiles (); int len = list.length; логический флаг = false; for (int i = 0; i <len; i ++) {file f = list [i]; String fn = f.getName (); if (f.isfile () && fn.lastindexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")); if (id.equals (fid)) {download (f, resp); flag = true; перерыв; }}} if (! flag) {notfound (contextpath, resp); }} else if (action.equals (delete)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } File file = new File (basePath); File [] list = file.listfiles (); int len = list.length; логический флаг = false; for (int i = 0; i <len; i ++) {file f = list [i]; String fn = f.getName (); if (f.isfile () && fn.lastindexof ("_")> -1) {string fid = fn.substring (fn.lastindexof ("_")); if (id.equals (fid)) {f.delete (); flag = true; перерыв; }}} if (flag) {// перенаправить на страницу списка файлов после обработки строки href1 = contextpath + list; Resp.sendredirect (href1); } else {notfound (contextpath, resp); }} else {show404 (contextpath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Printwrite = resp.getwriter (); Чтобы вернуться в список файлов </b> "); out.write (" </body> "); out.write (" </html> "); out.close ();} private void form (строка контекста, httpservletrespons resp.getwriter (); out.write ("<head> <title> form </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 ("<<input type = 'propect' value = 'upload'/> <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> операция не удалась! Файл не существует, или файл был удален! out.close (); } private void скачать (файл f, httpservletresponse resp) бросает ioException {string fn = f.getName (); String fileName = fn.substring (0, fn.lastindexof ("_")); System.out.println ("filename:" + filename); Resp.reset (); Resp.SetContentType («Приложение/октет-поток»); String encodingfilename = new String (fileName.getBytes ("gbk"), "iso8859-1"); System.out.println ("EncodingFilename:" + encodingFilename); Resp.Setheader («Содержание-распределение», «Приложение; файл» = " + encodingFilename); InputStream in = new FileInputStream (f); OutputStream Out = resp.getOutputStream (); байт [] b = новый байт [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); in.close (); out.close (); } private void List (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> List </title> </head>"); out.write ("<body>"); out.write ("<b> я хочу <a href = '" + href_u + "'> upload </a> </b> <br>"); out.write ("<table border = '1' style = 'Border-Collapse: Collapse; ширина: 100%; Margin-Top: 20px;'>"); out.write ("<thead>"); out.write ("<tr>"); out.write ("<Th> серийный номер </th> <Th> имя файла </th> <Th> операция </th>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); File file = new File (BasePath); File [] list = file.listfiles (); System.out .println ("basePath:" + basePath + "/tlist.size:" + list.length); int len = list.length; int no = 1; for (int i = 0; i <len; i ++) {file f = list [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 + загрузка + "? 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 refint (/" Вы уверены, что хотите его удалить?/"); '> Delete </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 Doget (httpservletrequest req, httpservletresponse resp), бросает ServletException, ioException {System.out.println ("Doget ..."); выполнить (req, resp); } public void Dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {System.out.println ("Dopost ..."); выполнить (req, resp); } частная строка getSuffix () {date date = new Date (); SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMmdDHMMMMSSSS"); Строка суффикс = sdf.format (date); вернуть суффикс; }}Фактически, класс uploadService может напрямую реализовать метод обслуживания без реализации методов Doget и Dopost.
Я не хочу ничего объяснять о приведенных выше сервлетах, просто прочитайте код для себя.
5. Диаграмма воспроизведения
1. Схема структуры проекта
Страница 2.404
/* будет соответствовать всем нулевым символам, поэтому путь на картинке будет соответствовать, который появится в другом в суждении в uploadservice, потому что действие в настоящее время является нулевым символом.
3. Страница списка файлов
4. Загрузить страницу формы
5. Скачать
6. Удалить
7. Файл не может быть найден. Если файл больше не существует на сервере при нажатии на удаление, то вы введете эту страницу.
8. упакованные проекты исходного кода и военные пакеты
Среди них z-upload-это проект исходного кода Eclipse, а z-upload.war-это готовый военный пакет
Во всем проекте есть только два пакета JAR, один Web.xml и один класс сервлета. Вы можете скопировать его из статьи и проверить. Если вы ленивы, вы можете скачать его.
http://download.csdn.net/detail/yunsyz/9569680, Специальное напоминание, загрузите его на 1 пункт.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.