En nuestro desarrollo web, muchas veces necesitamos cargar algunos archivos de la máquina al servidor web.
Por ejemplo: un sistema BBS, cuando los usuarios usan este sistema, pueden cargar algunas imágenes y documentos de la máquina al servidor. Entonces otros usuarios pueden descargar estos archivos. De esta manera, podemos programar la carga de archivo por nosotros mismos, pero una mejor manera es usar algunos componentes existentes para ayudarnos a darnos cuenta de esta función de carga.
Componentes de carga comunes:
Commons FileUpload por Apache
SuboLloadBean de Javazoom
jspsmartupload
Dirección de descarga de FileUpload:
http://commons.apache.org/fileupload/
Descargar: Commons-FileUpload-1.2.2-bin.zip Get: Commons-FileUpload-1.2.2.Jar
http://commons.apache.org/io/
Descargar: commons-io-1.4-bin.zip get: commons-io-1.4.Jar
cargar.jsp
código;
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8"%> <html> <fead> <title> Uso de la carga de bienes comunes para cargar el archivo </title> </head> <syle>* {Font-Family: "安体"; Font-size: 14px} </style> <body> <p align = "centro"> Seleccione el archivo que desea cargar </p> <form de formato = "form1" name = "form1" método = "post" action = "servlet/fileservlet" enctype = "multipart/form-data"> <table align = "Center"> <t> <td> type = "text" id = "name" size = "20"> </td> </tr> <tr> <tr> <td> cargar archivo: </td> <td> <input name = "file" type = "file" size = "20"> </td> </tr> <tr> <tr> <td> </td> <td> <input type = "Subt" Subt = "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "Subt" Subt "," name = "reset" value = "reset"> </td> </tr> </table> </form> </body> </html>FileUploadServlet.java Código:
paquete com.b510.example; import java.io.file; import java.io.ioexception; import java.util.*; import javax.servlet.servletConfig; import javax.servlet.servletContext; import javax.servlet.servlet.servletexception; javax.servlet.servletcontex. javax.servlet.http.httpservletRequest; import javax.servlet.http.httpServletResponse; importar org.apache.commons.fileUpload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemFactory; import org.apache.commons.fileupload.servlet.servletfileUpload;/** * * @author xhw * * @date 2011-7-7-26 * */public class FileUploadServlet Htttpservlet {private stertlet {private ster -77446253444830285257l; ServletContext privado SC; String String SavePath; Public void doget (httpservletRequest, respuesta, respuesta httpservletResponse) lanza ServletException, ioexception {dopost (solicitud, respuesta); } public void init (servletConfig config) {// Un parámetro de inicialización establecido en Web.xml SavePath = config.getInitParameter ("SavePath"); sc = config.getServletContext (); } public void dopost (httpservletRequest solicitud, respuesta httpservletResponse) lanza ServletException, ioexception {request.setcharacterEncoding ("UTF-8"); DiskFileItemFactory fábrica = new DiskFileItemFactory (); ServletFileUpload upload = new ServLetFileUpload (fábrica); intente {list elementos = upload.parserequest (solicitud); Iterador itr = items.iterator (); while (itr.hasnext ()) {fileItem item = (fileItem) itr.next (); if (item.isformfield ()) {System.out.println ("Nombre del parámetro de formulario:" + item.getFieldName () + ", valor de parámetro de formulario:" + item.getString ("utf-8")); } else {if (item.getName ()! = NULL &&! item.getName (). Equals (""))) {System.out.println ("Sobre el tamaño del archivo:" + item.getSize ()); System.out.println ("Tipo de archivo de carga:" + item.getContentType ()); // item.getName () Devuelve el nombre de ruta completo del archivo cargado en el cliente System.out.println ("Nombre del archivo de carga:" + item.getName ()); Archivo tempfile = nuevo archivo (elemento.getName ()); // Cargar archivo Guardar archivo archivo archivo = nuevo archivo (sc.getrealpath ("/") + savePath, tempfile.getName ()); item.write (archivo); request.setAttribute ("upload.message", "¡La carga de archivo fue exitosa!"); } else {request.setAttribute ("upload.message", "¡Sin archivo de carga seleccionado!"); }}}}} catch (FileUploadException e) {E.PrintStackTRace (); } catch (Exception e) {E.PrintStackTrace (); request.setAttribute ("upload.message", "¡Fallado de archivo!"); } request.getRequestDIsPatcher ("/uploadResult.jsp"). Forward (solicitud, respuesta); }}uploadResult.jsp Code:
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <! DocType html público "-// w3c // dtd html 4.01 transitional // en"> <html> <fead> <title> uploadResult </title> <seta http-equiv = "pRAgma" content = "no-cache"> <meta http-equiv = "cache-confontrol" content = "no-cache"> <meta http-equiv = "expires" content = "0"> <meta http-equiv = "Keywords" Keyword = "Keyword1, Keyword2, Keyword3"> <meta http-equiv = "Descripción" CONTITY = "CONTITY" ESTO ESTO ESTE IS MY PAGE "! rel = "stylesheet" type = "text/css" href = "styles.css"> -> </head> <body> $ {requestscope ['upload.message']} <a href = "/upload/uploadfile.jsp"> archivo de carga </a> </buerte> </html>web.xml
Código:
<? xml versión = "1.0" encoding = "utf-8"?> <web-app versión = "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/xml/ns/Javaee/web-app_2_5.xsd"> <Servlet> Componente </cription> <Spant-Name> Este es el nombre de visualización de mi componente J2EE </sippension-name> <Servlet-name> fileUploadServlet </servlet-name> <ervlet-class> com.b510.example.fileUploadservlet </servlet-class> <! -Parámetros de inicialización de la serie-> <init-param> <amamname> savePath </param-name> <amam-value> cargue </param-value> </init-param> </servlet> <ervlet-mapping> <ervlet-name> fileuploadservlet </servlet-name> <Url-pattern>/servlet/filservlet </urllame> <velceed-file-list> <calle-file> index.jsp </welcome-file> <welcome-file> uploadfile.jsp </leadde-file> </welcome-file-list> </beb-app>
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.