Em nosso desenvolvimento da Web, muitas vezes precisamos fazer upload de alguns arquivos da máquina para o servidor da Web.
Por exemplo: um sistema BBS, quando os usuários usam esse sistema, eles podem fazer upload de algumas imagens e documentos da máquina para o servidor. Em seguida, outros usuários podem baixar esses arquivos. Dessa forma, podemos programar o upload de arquivo sozinhos, mas uma maneira melhor é usar alguns componentes existentes para nos ajudar a realizar essa função de upload.
Componentes de upload comuns:
Commons FileUpload by Apache
O uploadbean de Javazoom
JSpsmartUpload
Endereço de download do FileUpload:
http://commons.apache.org/fileupload/
Download: Commons-FileUpload-1.2.2-bin.zip Get: Commons-FileUpload-1.2.2.jar
http://commons.apache.org/io/
Download: Commons-Io-1.4-bin.zip Get: Commons-Io-1.4.jar
upload.jsp
código;
<%@ Page Language = "java" contentType = "text/html; charset = utf-8"%> <html> <head> <title> usando o upload do Commons para fazer upload de arquivo </title> </head> <yoy>* {Font-Family: "安体"; font-size: 14px }</style><body><p align="center"> Please select the file you want to upload</p><form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"> <table align="center"> <tr> <td>Uploader: </td> <td> <input name = "name" type = "text" id = "name" size = "20"> </td> </tr> <tr> <td> File de upload: </td> <td> <nome de entrada = "arquivo" type = "file" size = "20"> </td> </tr> <t> <td> </td> <td> <input type = "reset" name = "reset" value = "redefinFileUploadServlet.java Código:
pacote com.b510.xample; importar java.io.file; importar java.io.ioException; importar java.util. javax.servlet.http.httpServletReQuest; importar javax.servlet.http.httpServletResponse; importar org.apache.commons.fileupload.fileitem; import orgache.commons.fileUplOad.fileUploadex org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * * @author XHW * * @date 2011-7-26 * */public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7744625344830285257L; ServletContext privado SC; private string savepath; Public void Doget (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {DoPost (solicitação, resposta); } public void init (servletConfig config) {// Um parâmetro de inicialização definido em web.xml savePath = config.getInitParameter ("salvAthath"); sc = config.getServletContext (); } public void DoPost (solicitação httpServletRequest, httpServletResponse Response) lança servletexception, ioexception {request.setcharacterencoding ("utf-8"); DiskFileItemFactory Factory = new DiskFileItemFactory (); ServletfileUpload upload = new ServletFileUpload (fábrica); tente {list itens = upload.parserequest (request); Iterator itr = items.iterator (); while (itr.hasnext ()) {fileItem item = (fileItem) itr.Next (); if (item.isformfield ()) {System.out.println ("Nome do parâmetro de formulário:" + item.getFieldName () + ", Valor do parâmetro do formulário:" + item.getString ("utf-8")); } else {if (item.getName ()! = null &&! item.getName (). Equals (""))) {System.out.println ("Upload do tamanho do arquivo:" + item.getSize ()); System.out.println ("Tipo de arquivo de upload:" + item.getContentType ()); // item.getName () Retorna o nome do caminho completo do arquivo carregado no cliente System.out.println ("Carregue o nome do arquivo:" + item.getName ()); Arquivo tempfile = novo arquivo (item.getName ()); // Faça o upload do arquivo Salvar arquivo do caminho do caminho = novo arquivo (sc.getRealPath ("/") + salvarpath, tempfile.getName ()); item.write (arquivo); request.setattribute ("upload.message", "o upload do arquivo foi bem -sucedido!"); } else {request.setAttribute ("upload.message", "nenhum arquivo de upload selecionado!"); }}}}} catch (fileUploadexception e) {e.printStackTrace (); } catch (Exceção e) {e.printStackTrace (); request.setattribute ("upload.message", "Falha no arquivo de upload!"); } request.getRequestDispatcher ("/uploadResult.jsp"). Forward (solicitação, resposta); }}uploadResult.jsp Código:
<%@ página de página = "java" import = "java.util.*" PageEncoding = "utf-8"%> <! Content = "no-cache"> <meta http-equiv = "cache-controle" content = "no-cache"> <meta http-equiv = "expire" content = "0"> <meta http (palavras-chave) rel = "Stylesheet" type = "text/css" href = "styles.css"> -> </ading> <body> $ {requestscope ['upload.message']} <a href = "/upload/uploadfile.jsp"> carregamento </a> </body> </html>web.xml
Código:
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee> http://java.sun.com/xmls/javaee> Componente j2ee </cription> <name-name> Este é o nome de exibição do meu componente j2ee </libe-name> <Servlet-name> fileUploadServlet </servlet-name> <Servlet-class> com.b510.example.fileUploadServlet </servlet-class> <! --Set initialization parameters --> <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/servlet/fileServlet</url-pattern> </servlet-mapping> <lorde-file-list> <lmed-fil-bile> index.jsp </chauty-File> <ldengre-fil-bile> uploadfile.jsp </ld-Welcome-File> </weld-File-list>
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.