No desenvolvimento do sistema de aplicativos da Web, as funções de upload e download de arquivos são funções muito usadas. Hoje, vamos falar sobre a implementação das funções de upload e download de arquivos no Javaweb.
1. Carregue um exemplo simples
JSP
<%@ Page Language = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! charset=UTF-8" /><title>File Upload and Download</title></head><body><form action="${pageContext.request.contextPath}/UploadServlet" enctype="multipart/form-data" method="post"> Upload user: <input type="text" name="username" /> <br /> Upload file 1: <input type="file" name = "FILE1" /> <BR /> FILHO 2: <input type = "file" name = "file2" /> <r /> <input type = "submit" value = "upload" /> < /form> <br /> $ {requestscope.message} < /body> < /html>Servlet
Public void Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {try {// 1. Obtenha a fábrica de Parsers DiskFileItemFactory Factory = new DiskFileItemFactory (); // 2. Obtenha o Parser ServletFileUpload upload = new ServletFileUpload (Factory); // 3. Determinar o tipo de formulário de upload if (! Upload.ismultipartContent (request)) {// upload O formulário é um formulário normal e, em seguida, obtenha os dados da maneira tradicional e retorne; } // Para fazer upload de um formulário, o analisador é chamado para analisar a lista de dados de upload <FileItem> list = upload.parserequest (request); // fileItem // transipula a lista para obter o primeiro objeto de dados de dados do item de entrada do item de entrada para (item de fileItem: list) {if (item.isformfield ()) {// o que você obtém é o nome de string de entrada normal = item.getfieldName (); // Obtenha o nome do item de entrada Valor da string = item.getString (); System.out.println (nome + "=" + valor); } else {// Obtenha o item de entrada do upload string filename = item.getName (); // recebe o nome do arquivo carregado c:/documentos e configurações/thinkpad/desktop/1.txt filename = filename.substring (filename.lastindexof ("//")+1); InputStream in = item.getInputStream (); // recebe dados carregados int len = 0; buffer de byte [] = novo byte [1024]; // O diretório usado para salvar arquivos carregados deve proibir o mundo exterior de acessar diretamente a String savePath = this.getServletContext (). GetRealPath ("/web-inf/upload"); System.out.println (salvath); FileOutputStream Out = new FileOutputStream (SavePath + "/" + FileName); // Escreva o arquivo no diretório de upload while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.Close (); request.setAttribute ("mensagem", "Upload de sucesso"); }}}} Catch (Exceção e) {request.setAttribute ("mensagem", "Falha no upload"); E.PrintStackTrace (); }}2. Função de upload modificada:
Notas:
1. Código chinês iluminado para fazer upload de nomes de arquivos e código ilegal chinês para fazer upload de dados
upload.setheadeRencoding ("UTF-8"); // Resolva código ilegal chinês para fazer upload de nomes de arquivos
// O formulário é carregado para arquivo, a codificação de solicitação é inválida e só pode ser convertida manualmente
1.1 Valor = new String (value.getBytes ("ISO8859-1"), "UTF-8");
1.2 String Value = Item.getString ("UTF-8");
2. Para garantir a segurança do servidor, os arquivos de upload devem ser colocados em diretórios que não possam ser acessados diretamente pelo mundo exterior.
3. Para evitar a sobrescrição de arquivos, um nome de arquivo exclusivo deve ser gerado para fazer upload do arquivo.
4. Para evitar que muitos arquivos apareçam em um diretório, você precisa usar o algoritmo de hash para interromper o armazenamento.
5. Para limitar o valor máximo dos arquivos carregados, você pode usar o: servletfileUpload.setFilesizEMAX (1024) Método e captura:
FILEUPLOADBASE.FILESIZELIMITEXEDEDEDEXCECTIÇA Exceção para fornecer instruções fáceis de usar
6. Se você deseja garantir que o arquivo temporário seja excluído, você deve ligar para o método item.Delete após o processamento do arquivo de upload.
7. Para limitar o tipo de arquivo carregado: Ao receber o nome do arquivo carregado, determine se o nome do sufixo é legal.
8. Ouça o progresso do upload do arquivo:
ServletfileUpload upload = new ServletFileUpload (fábrica); upload.setProgressListener (new ProgressListener () {public void update (longo pbytesread, pcOntentLength LongLeng, int arg2) {System.out.println ("O tamanho do arquivo é:" + pcontentLength + ", atualmente processado:" + pbytesread);}}); 9. Adicione dinamicamente os itens de entrada de upload do arquivo na página da web
função addinput () {var div = document.getElementById ("arquivo"); var input = document.createElement ("input"); input.type = "arquivo"; input.Name = "FileName"; var del = document.createElement ("entrada"); del.Type = "Button"; del.value = "excluir"; del.OnClick = function d () {this.parentnode.parentnode.removeChild (this.parentnode); } var inerdiv = document.createElement ("div"); inerdiv.appendChild (entrada); Innerdiv.AppendChild (Del); Div.AppendChild (InnerDiv); }Carregue JSP:
<%@ página linguagem = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! addinput () {var div = document.getElementById ("arquivo"); var input = document.createElement ("input"); input.type = "arquivo"; input.Name = "FileName"; var del = document.createElement ("entrada"); del.Type = "Button"; del.value = "excluir"; del.OnClick = function d () {this.parentnode.parentnode.removeChild (this.parentnode); } var inerdiv = document.createElement ("div"); inerdiv.appendChild (entrada); Innerdiv.AppendChild (Del); Div.AppendChild (InnerDiv); } </script> </ad Head> <body> <formulário action = "" Enctype = "mutLipart/form-data"> </morm> <table> <tr> <td> upload Usuário: </td> <td> <input type = "text" name = "username"> </td> </td> <troux> <troux> <troux> <tr-GROURT) value = "adicione arquivo de upload" onclick = "addinput ()"> </td> </tr> <tr> <td> </td> <td> <div id = "file"> </div> </td> </td> </tr> </ tabela> </body </body> </html>Carregar servlet
classe pública uploadServlet1 estende httpServlet {public void Doget (solicitação HttPervletRequest, httpServletResponse Response) lança servletexception, ioexception {//request.getparameter("UserName "); // **** Request.Setcharacterencoding ("UTF-8"); // O formulário é carregado para o arquivo e a codificação de solicitação é inválida // obtém o arquivo carregado salvAth = this.getServletContext (). GetRealPath ("/web-inf/upload"); tente {DiskFileItemFactory Factory = new DiskFileItemFactory (); Factory.SetRepository (novo arquivo (this.getServletContext (). getRealPath ("/web-inf/temp"))); ServletfileUpload upload = new ServletFileUpload (fábrica); /*Upload.SetProgressListener(New ProgressListener () {public void update (pbytesRead longo, longo pcOntentLength, int arg2) {System.out.println ("Tamanho do arquivo é:" + pcOntentlength + ", atualmente processado:" + pbyTesread);}}); // Resolva o código iluminado chinês de fazer upload de nomes de arquivos se (! Upload.ismultipartContent (request)) {// obtenha dados de maneira tradicional retornar; } /*upload.setFilesizEMAX(1024); upload.SetSizEMAX (1024*10);*/ list <FileItem> list = upload.parserequest (solicitação); para (Item FileItem: List) {if (item.isformfield ()) {// Os dados dos itens de entrada comuns são encapsulados no nome da string fileItem = item.getFieldName (); String value = item.getString ("UTF-8"); // valor = new String (value.getBytes ("ISO8859-1"), "UTF-8"); System.out.println (nome + "=" + valor); } else {// O arquivo de upload é encapsulado no arquivo string filename = item.getName (); // Os arquivos enviados por diferentes navegadores são diferentes c: //b/1.txt 1.txt System.out.println (nome do arquivo); if (nome do arquivo == null || filename.trim (). Equals ("")) {continue; } nome do arquivo = nome do arquivo.substring (nome do arquivo.lastIndexof ("//")+1); InputStream in = item.getInputStream (); String savefilename = makefilename (nome do arquivo); // Obtenha o nome do arquivo salvo String realSavePath = MakePath (saveFileName, salvAth); // Obtenha o arquivo Salvar o diretório FileOutputStream out = new FileOutputStream (RealSavePath + "//" + saveFileName); buffer de byte [] = novo byte [1024]; int len = 0; while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.Close (); item.Delete (); // excluir arquivo temporário}}} catch (fileUploadbase.filesizElimitexcedException e) {e.printStackTrace (); request.setAttribute ("mensagem", "o arquivo excede o valor máximo!!"); request.getRequestDispatcher ("/message.jsp"). Forward (solicitação, resposta); retornar; } catch (Exceção e) {e.printStackTrace (); }} public string string makefilename (string filename) {//2.jpg return uuid.randomuuid (). tostring () + "_" + nome do arquivo; } public string makepath (string filename, string savepath) {int hashcode = filename.hashcode (); int dir1 = hashcode & 0xf; // 0--15 int Dir2 = (HashCode & 0xf0) >> 4; // 0-15 String dir = savePath + "//" + dir1 + "//" + dir2; // upload/2/3 upload/3/5 arquivo de arquivo = novo arquivo (dir); if (! file.exists ()) {file.mkdirs (); } retornar dir; } public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {doget (solicitação, resposta); }}3. Função de download
// Liste todos os arquivos de download no site public class ListFileServlet estende httpServlet {public void Doget (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {string filePath = this.getSletContext (). Mapa mapa = new hashmap (); listfile (novo arquivo (filepath), mapa); request.setAtattribute ("mapa", mapa); request.getRequestDispatcher ("/listfile.jsp"). Forward (solicitação, resposta); } public void listfile (arquivo de arquivo, mapa mapa) {if (! file.isfile ()) {file files [] = file.listfiles (); para (arquivo f: arquivos) {listfile (f, mapa); }} else {string realname = file.getName (). substring (file.getName (). indexof ("_")+1); //9349249849-88343-8344_A_FAN_DAVI.AVI MAP.PUPT (FILE.GETNAME (), REALNAME); }} public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {doget (solicitação, resposta); }}display jsp
<%@ Page Language = "java" import = "java.util. Transitória // pt "> <html> <head> <title> meu jsp 'listfile.jsp' página de partida </ititle> </ading> <body> <c: foreach var =" me "itens =" $ {map} "> <c: url value ="/servlet/download "var =" downurl "> <c: value = "$ {me.key}"> </c: param> </c: url> $ {me.value} <a href = "$ {Downurl}"> Download </a> <br/> </c: foreach> </body> </html>Baixe o servlet de processamento
classe pública DownloadServlet estende httpServlet {public void Doget (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {string filename = request.getParameter ("filename"); //23239283-92489-avatar.avi filename = new String (filename.getbytes ("ISO8859-1"), "UTF-8"); String Path = MakePath (nome do arquivo, this.getServletContext (). GetRealPath ("/web-inf/upload")); Arquivo de arquivo = novo arquivo (caminho + "//" + nome do arquivo); if (! file.exists ()) {request.setAttribute ("mensagem", "o recurso que você deseja baixar foi excluído !!"); request.getRequestDispatcher ("/message.jsp"). Forward (solicitação, resposta); retornar; } String realname = filename.substring (filename.indexof ("_")+1); Response.setheader ("Content-Disposition", "Applement; filename =" + urlencoder.encode (nome real, "utf-8")); FileInputStream in = new FileInputStream (caminho + "//" + nome do arquivo); OutputStream out = Response.getOutputStream (); buffer de byte [] = novo byte [1024]; int len = 0; while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.Close (); } public string makepath (string filename, string savepath) {int hashcode = filename.hashcode (); int dir1 = hashcode & 0xf; // 0--15 int Dir2 = (HashCode & 0xf0) >> 4; // 0-15 String dir = savePath + "//" + dir1 + "//" + dir2; // upload/2/3 upload/3/5 arquivo de arquivo = novo arquivo (dir); if (! file.exists ()) {file.mkdirs (); } retornar dir; } public void DoPost (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {doget (solicitação, resposta); }}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.