En el desarrollo del sistema de aplicaciones web, las funciones de carga y descarga de archivos son funciones comúnmente utilizadas. Hoy, hablemos sobre la implementación de las funciones de carga y descarga de archivos en Javaweb.
1. Sube un ejemplo simple
JSP
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <! DocType html público "-// w3c // dtd xhtml 1.0 transitional // en"> <html> <Head> <meta http-outiv = "content-type" contenido = "contenido"/"html> <fead> <Head> <Ett> <feT> <Ext>; charset = utf-8 "/> <title> Carga de archivo y descarga </title> </head> <body> <form de acción =" $ {pageContext.request.contextpath}/uploadServlet "Inctype =" multipart/form-data "método =" post "> Úser de carga: <input type =" text "name =" userName "/> <br/> uptiew file 1: <100 type" name = "File1" /> <Br /> Subload File 2: <input type = "file" name = "file2" /> <Br /> <input type = "subt" value = "upload" /> < /form> <br /> $ {requestscope.message} </body> </html>Servir
public void doget (HTTPServletRequest Solicitud, respuesta httpservletResponse) lanza ServletException, ioexception {try {// 1. Obtenga la fábrica de fábrica de fábrica analiza Factory = new DiskFileItemFactory (); // 2. Obtenga el analizador ServletFileUPLOAD SUPERD = new ServLetFileUpload (fábrica); // 3. Determine el tipo de formulario de carga if (! Upload.ismultipartContent (request)) {// cargar el formulario es una forma normal, luego obtenga los datos de la manera tradicional y return; } // Para cargar un formulario, se llama al analizador para analizar la lista de datos de carga <StilEitem> list = upload.parserequest (solicitud); // fileItem // Transipule la lista para obtener el primer objeto de datos de entrada de entrada de entrada para el objeto FileItem para (fileItem item: list) {if (item.isformfield ()) {// Lo que obtiene es la entrada normal Elemento name = item.getFieldName (); // Obtenga el nombre del valor de la cadena de elementos de entrada = item.getString (); System.out.println (nombre + "=" + valor); } else {// Obtener el elemento de entrada de carga String FileName = item.getName (); // Obtener nombre de archivo cargado c:/documentos y configuración/thinkpad/escritorio/1.txt filename = filename.substring (filename.lastindexof ("//")+1); InputStream in = item.getInputStream (); // obtener datos cargados int len = 0; byte buffer [] = nuevo byte [1024]; // El directorio utilizado para guardar archivos cargados debe prohibir que el mundo exterior acceda directamente a String SavePath = this.getServletContext (). GetRealPath ("/Web-Inf/upload"); System.out.println (SavePath); FileOutputStream out = new FileOutputStream (SavePath + "/" + FileName); // Escribir archivo en el directorio de carga while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.close (); request.setAttribute ("Mensaje", "Subir éxito"); }}}} capt (excepción e) {request.setAttribute ("mensaje", "cargar fallido"); E.PrintStackTrace (); }}2. Función de carga modificada:
Notas:
1. Código confuso chino para cargar nombres de archivos y código confuso chino para cargar datos
subir.setheaderEncoding ("UTF-8"); // Resolver el código confuso chino para cargar nombres de archivos
// El formulario se carga para el archivo, la codificación de solicitud no es válida y solo se puede convertir manualmente
1.1 value = new String (value.getBytes ("ISO8859-1"), "UTF-8");
1.2 Valor de cadena = item.getString ("UTF-8");
2. Para garantizar la seguridad del servidor, los archivos de carga deben colocarse en directorios a los que el mundo exterior no puede acceder directamente.
3. Para evitar la sobrescritura del archivo, se debe generar un nombre de archivo único para cargar el archivo.
4. Para evitar que aparezcan demasiados archivos en un directorio, debe usar el algoritmo hash para romper el almacenamiento.
5. Para limitar el valor máximo de los archivos cargados, puede usar el método: ServletFileUpload.SetFilesizEmax (1024) y captura:
FileUploadbase.FililesEnElimiteExedEdException Exception para dar indicaciones para el usuario
6. Si desea asegurarse de que se elimine el archivo temporal, debe llamar al método elemento. Delete después de procesar el archivo de carga.
7. Para limitar el tipo de archivo cargado: al recibir el nombre del archivo cargado, determine si el nombre del sufijo es legal.
8. Escuche el progreso de carga de archivos:
ServletFileUpload upload = new ServLetFileUpload (fábrica); upload.setProgressListener (new ProgressListener () {public void Update (long pbytesread, long pcontentLength, int arg2) {system.out.println ("El tamaño del archivo es:" + pContentLength + ", actualmente procesado:" + pbytesread);}}); 9. Agregar dinámicamente los elementos de entrada de carga de archivos en la página web
function addInput () {var div = document.getElementById ("archivo"); var input = document.createElement ("entrada"); input.type = "archivo"; input.name = "FileName"; var del = document.createElement ("entrada"); del.type = "botón"; del.value = "eliminar"; del.onclick = function d () {this.parentnode.parentnode.removechild (this.parentnode); } var innerDiv = document.createElement ("div"); innerdiv.appendChild (entrada); innerdiv.appendchild (del); div.appendchild (InnerDiv); }Subir JSP:
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <! DocType html público "-// w3c // dtd html 4.01 transitional // en"> <html> <fead> <title> my jsp 'carging2.jsp orag addInput () {var div = document.getElementById ("archivo"); var input = document.createElement ("entrada"); input.type = "archivo"; input.name = "FileName"; var del = document.createElement ("entrada"); del.type = "botón"; del.value = "eliminar"; del.onclick = function d () {this.parentnode.parentnode.removechild (this.parentnode); } var innerDiv = document.createElement ("div"); innerdiv.appendChild (entrada); innerdiv.appendchild (del); div.appendchild (InnerDiv); } </script> </head> <body> <form de acción = "" enctype = "mutlipart/form de formato"> </form> <table> <tr> <td> cargar usuario: </td> <td> <input type = "text" name = "username"> </td> </tr> <tr> <tr> <td> iba Subiendo el archivo "onClick =" addInput () "> </td> </tr> <tr> <td> </td> <td> <div ID =" file "> </div> </td> </td> </tr> </table> </body> </html>Subir servlet
public class uploadServlet1 extiende httpservlet {public void doget (httpservletRequest solicitud, respuesta httpservletreSponse) lanza ServletException, ioexception {//request.getparameter("username "); // **** Solicitud de error. SetcharacterEncoding ("UTF-8"); // El formulario se carga para el archivo, y la codificación de solicitud no es válida // Obtenga el archivo cargado SavePath = this.getServletContext (). GetRealPath ("/web-Inf/upload"); intente {diskFileItemFactory factory = new DiskFileItemFactory (); factory.setRepository (nuevo archivo (this.getServletContext (). GetRealPath ("/Web-INF/TEMP")); ServletFileUpload upload = new ServLetFileUpload (fábrica); /*upload.setProgressListener(New ProgressListener () {public void Update (long pbytesread, long pcontentLength, int arg2) {system.out.println ("El tamaño del archivo es:" + pcontentLength + ", actualmente procesado:" + pbytesread);}}});*/ upload.setheaderencoding ("" ");"); // Resuelve el código chino de carga de los nombres de los archivos si (! Upload.ismultipartContent (request)) {// Obtener datos de retorno tradicional de la manera tradicional; } /*upload.setFillesizeMax(1024); upload.setsizeMax (1024*10);*/ list <StilEitem> list = upload.parserequest (solicitud); for (fileItem item: list) {if (item.isformfield ()) {// Los datos de los elementos de entrada ordinarios se encapsulan en el nombre de cadena FileItem = item.getFieldName (); Valor de cadena = item.getString ("UTF-8"); // value = new String (value.getBytes ("ISO8859-1"), "UTF-8"); System.out.println (nombre + "=" + valor); } else {// El archivo de carga está encapsulado en la cadena fileitem filename = item.getName (); // Los archivos enviados por diferentes navegadores son diferentes c: /a/b/1.txt 1.txt system.out.println (nombre de archivo); if (filename == null || filename.trim (). Equals ("")) {continuar; } filename = filename.substring (filename.lastIndexof ("//")+1); InputStream in = item.getInputStream (); String saveFileName = MakefileName (FileName); // Obtenga el nombre de la cadena guardada de archivo realSavePath = MakEpath (SaveFileName, SavePath); // Obtenga el directorio de archivo Guardar FileOutputStream Out = New FileOutputStream (RealSavePath + "//" + SaveFileName); byte buffer [] = nuevo byte [1024]; int len = 0; while ((len = in.read (buffer))> 0) {out.write (buffer, 0, len); } in.close (); out.close (); item.delete (); // Eliminar archivo temporal}}} Catch (fileUploadBase.FileSizeLimiteExedException e) {E.PrintStackTrace (); request.setAttribute ("Mensaje", "¡El archivo excede el valor máximo!!"); request.getRequestDIsPatcher ("/Message.jsp"). Foring (solicitud, respuesta); devolver; } catch (Exception e) {E.PrintStackTrace (); }} public String MakeFileName (String FileName) {//2.jpg return uuid.randomuuid (). toString () + "_" + filename; } public String Makepath (String FileName, String SavePath) {int hashcode = filename.hashCode (); int dir1 = hashcode & 0xf; // 0--15 int dir2 = (hashcode & 0xf0) >> 4; // 0-15 cadena dir = SavePath + "//" + Dir1 + "//" + Dir2; // cargar/2/3 cargar/3/5 archivo de archivo = nuevo archivo (dir); if (! file.exists ()) {file.mkdirs (); } return dir; } public void dopost (httpservletRequest solicitud, respuesta httpservletreSponse) lanza ServletException, ioexception {doget (solicitud, respuesta); }}3. Función de descarga
// Enumere todos los archivos de descarga en el sitio web ListSpLingFileServlet extiende httpservlet {public void doget (httpservletRequest request, httpServletResponse respuesta) lanza servletException, ioException {string filepath = this.getServletContext (). GetRealpath ("/webinf/upload"); Mapa map = nuevo hashmap (); ListFile (nuevo archivo (FilePath), MAP); request.setAttribute ("map", map); request.getRequestDIsPatcher ("/listFile.jsp"). Foring (solicitud, respuesta); } public void listFile (archivo de archivo, map map) {if (! file.isfile ()) {file file [] = file.listFiles (); for (archivo f: archivos) {listFile (f, map); }} else {string realName = file.getName (). Substring (file.getName (). indexOf ("_")+1); //9349249849-88343-8344_a_fan_davi.avi map.put (file.getName (), realName); }} public void dopost (httpservletRequest solicitud, respuesta httpservletResponse) arroja servletException, ioexception {doget (solicitud, respuesta); }}pantalla JSP
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> < Transitional // en "> <html> <fead> <title> my jsp 'listFile.jsp' Página inicial </title> </head> <body> <c: foreach var =" me "elementos =" $ {map} "> <c: url value ="/servlet/descargaServlet "var =" downurl "> <c: param name =" filename "" "" " valor = "$ {me.key}"> </c: param> </c: url> $ {me.value} <a href = "$ {downurl}"> descargar </a> <br/> </c: foreach> </body> </html>Descargar el servlet de procesamiento
Public Class downloadServlet extiende httpservlet {public void doget (httpservletRequest solicitud, respuesta httpservletResponse) lanza ServletException, ioexception {string filename = request.getParameter ("filename"); //23239283-92489-avatar.avi filename = new String (FileName.getBytes ("ISO8859-1"), "UTF-8"); String path = makepath (nombre de archivo, this.getServletContext (). GetRealPath ("/web-Inf/upload")); Archivo archivo = nuevo archivo (ruta + "//" + nombre de archivo); if (! file.Exists ()) {request.setAttribute ("Mensaje", "El recurso que desea descargar ha sido eliminado!"); request.getRequestDIsPatcher ("/Message.jsp"). Foring (solicitud, respuesta); devolver; } String realName = filename.substring (filename.indexof ("_")+1); Respuesta.Setheader ("Disposición de contenido", "Adjunto; FileName =" + Urlencoder.encode (RealName, "UTF-8")); FileInputStream in = new FileInputStream (PATH + "//" + FileName); OutputStream out = Response.getOutputStream (); byte buffer [] = nuevo 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 cadena dir = SavePath + "//" + Dir1 + "//" + Dir2; // cargar/2/3 cargar/3/5 archivo de archivo = nuevo archivo (dir); if (! file.exists ()) {file.mkdirs (); } return dir; } public void dopost (httpservletRequest solicitud, respuesta httpservletreSponse) lanza ServletException, ioexception {doget (solicitud, respuesta); }}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.