Não tenho nada a fazer, então escrevi um servlet para implementar a função de upload e download. Depois de iniciar o serviço, você pode ser um pequeno servidor de arquivos em uma LAN.
1. Preparação
Baixe dois pacotes JAR:
Commons-FileUpload-1.3.1.Jar
Commons-io-2.2.jar
2. Crie um projeto da web
Meu projeto é chamado: z-upload
3. Configure 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/xmls/javaee/web-web-web-web-web--/java.sun.com/xmls/javaeeeee/web-web-web-web-web-web-web-web-web-web-web-web-web-web-web-/java.sun.com/ <lame-name> z-upload </libe-name> <Verlet> <Servlet-name> uploadservice </servlet-name> <Servlet-class> com.syz.servlet.uploadservice </servlet-class> </servlet> <Verlet-Mapatter> <loml-name> UrtleTice " </servlet-mapping> </braypp>
A partir da configuração acima, podemos ver que minha classe servlet é upload service e o URL correspondente é /*, o que significa corresponder a todos os URLs de acesso.
4. Escreva aula de servlet
pacote com.syz.servlet; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.io.ioException; importação java.io.inprintStream; importância java.io.outstream; java.util.date; importar java.util.iterator; importar java.util.list; importar javax.servlet.servletContext; importar javax.servlet.servletexception; importtlet.htlet.htlet.htlet.http.httpslets; javax.servlet.http.httpServletResponse; importar org.apache.commons.fileupload.fileitem; importar org.apache.commons.fileupload.fileuploadexception; import orgache.commons.fileUPLOAD.PRESSLISTER; org.apache.commons.fileupload.disk.diskfileitemfactory; importar org.apache.commons.fileupload.servlet.servletfileUpload; classe pública uploadServlet estende httpServlet {public static final string list = "/list"; public static final string form = "/form"; public static final string handle = "/handle"; public static final string download = "/download"; public static final string final Delete = "/Delete"; public static final string upload_dir = "/upload"; private estático final serialversionUid = 2170797039752860765L; public void Execute (httpServletRequest req, httpServletResponse resp) lança 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 (); // o caminho base para fazer upload da sequência de arquivos basalEpath = servletContext.getRealPath (upload_dir); // Caminho de contexto String contextPath = servletContext.getContextPath (); System.out.println ("contextPath:" + contextPath); // caminho após interceptar a ação da string de contexto = uri.substring (contextPath.Length ()); System.out.println ("Ação:" + ação); // processamento diferente é realizado de acordo com diferentes ações se (action.equals (form)) {form (contextpath, resp); } else if (Action.equals (handle)) {boolean ismultipart = servletfileUpload.ismultipartContent (req); System.out.println ("ismultipart:" + ismultipart); if (! ismultipart) {return; } DiskFileItemFactory Factory = new DiskFileItemFactory (); Repositório de arquivo = (arquivo) servletContext .getAttribute (servletContext.tempdir); System.out.println ("repositório:" + repositório.getabsolutepath ()); System.out.println ("Basepath:" + base); Factory.SetSizETHreshold (1024 * 100); Factory.SetRepository (repositório); ServletfileUpload upload = new ServletFileUpload (fábrica); // Crie um ouvinte ProgressListener ProgressListener = new ProgressListener () {public void update (pbytesread longo, longo pcOntentLength, int pitems) {System.out.println ("Tamanho atual do arquivo:" + pcontentlength + "/t já processado:" + pbytesread); }}; upload.setProgressListener (ProgressListener); List <FileItem> itens = null; tente {itens = upload.parserequest (req); System.out.println ("Tamanho dos itens:" + items.size ()); Iterator <FileItem> item = items.iterator (); while (ite.hasnext ()) {fileItem item = item.Next (); if (item.isformfield ()) {// Handle formfield} else {// lide o arquivo string fieldname = item.getfieldName (); String filename = item.getName (); FILENAME = FILENAME.SUBSTRING (FILENAME.LASTIndexOF (File.separator) + 1); String contentType = item.getContentType (); boolean isinMemory = item.isinMemory (); sizeinbytes longos = item.getSize (); System.out.println (fieldname + "/t" + nome do arquivo + "/t" + contentType + "/t" + isinMemory + "/t" + sizeinbytes); Arquivo Arquivo = novo arquivo (Basepath + "/" + FileName + "_" + getSuffix ()); // item.write (arquivo); InputStream in = item.getInputStream (); OutputStream out = new FileOutputStream (arquivo); byte [] b = novo byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); in.Close (); out.Close (); }} // redireciona para a página Lista de arquivos após o processamento da string href1 = listathPath + list; resp.sendRedirect (href1); } catch (fileUploadexception e) {e.printStackTrace (); } catch (Exceção e) {e.printStackTrace (); }} else if (action.equals (list)) {list (contextPath, bashepath, resp); } else if (action.equals (download)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Arquivo de arquivo = novo arquivo (baseepath); Arquivo [] list = file.listfiles (); int len = list.length; bandeira booleana = false; for (int i = 0; i <len; i ++) {arquivo 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); bandeira = true; quebrar; }}} if (! Flag) {notfound (contextPath, resp); }} else if (action.equals (exclate)) {string id = req.getParameter ("id"); System.out.println ("id:" + id); if (id == null) {return; } Arquivo de arquivo = novo arquivo (baseepath); Arquivo [] list = file.listfiles (); int len = list.length; bandeira booleana = false; for (int i = 0; i <len; i ++) {arquivo 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 (); bandeira = true; quebrar; }}} if (sinalizador) {// redireciona para a página da lista de arquivos após o processamento da string href1 = contextPath + list; resp.sendRedirect (href1); } else {notfound (contextpath, resp); }} else {show404 (contextPath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- PrintWriter Out = resp.getWriter (); retornar para a lista de arquivos </b> "); out.write (" </body> "); out.write (" </html> "); out.close ();} forma privada (string contextPath, httpSertletResponse resp) lança IoException {resp.setContentType (" textRexeTr; String href1 = listathpath +; out.write ("<head> <title> formulário </title> </head>"); out.write ("<body>"); out.write ("<b> <a href = '" + href1 + "'> clique </a> para retornar à lista de arquivos </b>"); out.Write ("<form ação = 'handle' método = 'post' Enctype = 'Multipart/form-data' style = 'margin-top: 20px;'>"); out.write ("<nome de entrada = 'arquivo' type = 'file'/> <br>"); out.write ("<type de entrada = 'submeter' value = 'upload'/> <br>"); out.write ("</morm>"); out.write ("</body>"); out.write ("</html>"); out.Close (); } private void notfound (string contextpath, httpServletResponse resp) lança ioexception {resp.setContentType ("text/html; charset = utf-8"); PrintWriter out = resp.getWriter (); String href1 = contextPath + list; out.write ("<html> <body> <b> Operação falhou! O arquivo não existe ou o arquivo foi excluído! out.Close (); } Download privado de void (arquivo f, httpServletResponse resp) lança ioexception {string fn = f.getName (); String filename = fn.substring (0, fn.LastIndexOf ("_")); System.out.println ("nome do arquivo:" + nome do arquivo); resp.Reset (); resp.setContentType ("Application/Octet-Stream"); String codingfilename = new string (filename.getbytes ("gbk"), "iso8859-1"); System.out.println ("codingfilename:" + codingfilename); resp.setheader ("Content-Disposition", "Applement; filename =" + codingfilename); InputStream in = new FileInputStream (f); OutputStream out = resp.getOutputStream (); byte [] b = novo byte [1024]; int n = 0; while ((n = in.read (b))! = -1) {out.write (b, 0, n); } out.flush (); in.Close (); out.Close (); } Lista de vazios privados (String contextPath, String BasEpath, httpServletResponse resp) lança 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> eu quero <a href = '" + href_u + "'> upload </a> </b> <br>"); out.write ("<tabela borda = '1' estilo = 'colapso de borda: colapso; largura: 100%; margem de margem: 20px;'>"); out.write ("<Tead>"); out.write ("<tr>"); out.Write ("<th> Número de série </th> <th> Nome do arquivo </th> <th> operação </th>"); out.write ("</tr>"); out.write ("</tr>"); out.write ("<tbody>"); Arquivo de arquivo = novo arquivo (base); Arquivo [] 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 ++) {arquivo 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 + download + "? Id =" + id; String href2 = contextpath + excluir + "? Id =" + id; Stringbuilder sb = new stringbuilder (); sb.append ("<tr>"); sb.append ("<td>"); sb.append (não ++); sb.append ("</td>"); sb.append ("<td>"); sb.append (nome do arquivo); sb.append ("</td>"); sb.append ("<td>"); sb.append ("<a href = '"); sb.append (href1); sb.append ("'> download </a> <a href ='"); sb.append (href2); sb.append ("'OnClick =' Return confirm (/" Você tem certeza de que deseja excluí -lo?/"); '> excluir </a>"); sb.append ("</td>"); sb.append ("</tr>"); out.write (sb.toString ()); }} out.write ("</tbody>"); out.Write ("</ tabela>"); out.write ("</body>"); out.write ("</html>"); out.Close (); } public void Doget (httpServletRequest req, httpServletResponse resp) lança servletexception, ioexception {System.out.println ("Doget ..."); executar (req, resp); } public void DoPost (httpServletRequest req, httpServletResponse resp) lança servletexception, ioexception {System.out.println ("DoPost ..."); executar (req, resp); } private string getSuffix () {date = new Date (); SimpledateFormat sdf = new SimpleDateFormat ("yyyymmddhhmmsssss"); String sufix = sdf.format (data); devolver sufixo; }}De fato, a classe UploadService pode implementar diretamente o método de serviço sem implementar os métodos DOGET e DOPOST.
Não quero explicar nada sobre os servlets acima, basta ler o código para si mesmo.
5. Diagrama de reprodução
1. Diagrama da estrutura do projeto
Página 2.404
/* corresponderá a todos os caracteres nulos, para que o caminho da imagem corresponda, que aparece em outra pessoa no julgamento IF no uploadservice, porque a ação neste momento é um caractere nulo.
3. Página da lista de arquivos
4. Página de formulário de upload
5. Download
6. Exclua
7. O arquivo não pode ser encontrado. Se o arquivo não existir mais no servidor quando você clicar em Excluir, você inserirá esta página.
8. Projetos de código -fonte embalados e pacotes de guerra
Entre eles, o Z-Upload é o projeto do código-fonte do Eclipse, e Z-upload.war é o pacote de guerra Ready
Existem apenas dois pacotes JAR em todo o projeto, um web.xml e uma classe de servlet. Você pode copiá -lo do artigo e testá -lo. Se você é preguiçoso, pode baixá -lo.
http://download.csdn.net/detail/yunyz/9569680, lembrete especial, faça o download por 1 ponto.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.