Spring MVC Archivo Carga y descarga, como sigue:
(1) Importación de paquetes de jar: Ant.Jar, Commons-FileUpload.jar, connom-io.jar.
(2) Agregue SRC/context/despachador.xml
<bean id = "multipartresolver" p: defaultEncoding = "utf-8" />
Tenga en cuenta que debe agregar contenido al cabezal, como se muestra a continuación después de agregar:
<beans default llazy-init = "true" xmlns = "http://www.springframework.org/schema/beans" xmlns: p = "http://www.springframework.org/schema/p" " xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/Beans/Spring-Beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.0.xsdd.sddd.sxsdsd. http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
(3) Agregue la clase de herramienta FileOpererutil.java
/ ** * * @author geoin */ paquete com.geloin.spring.util; import java.io.bufferedInputStream; import java.io.bufferedOutputStream; import java.io.file; import java.io.fileInputStream; import java.io.fileOutputStream; import java.text.simpledateFormat; import java.util.arrayList; import java.util.date; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; importar org.apache.tools.zip.zipentry; importar org.apache.tools.zip.zipoutputstream; importar org.springframework.util.filecopyutils; importar org.springframework.web.multipart.multipartfile; importar org.springframework.web.multipart.multiparthttpservletRequest; public class FileOperateUtil {private static final String realName = "RealName"; storename storename de la estática privada = "storeName"; size de cadena final estática privada = "tamaño"; String final de cadena final estática privada = "Suffix"; static final static finalmente contentType = "ContentType"; String final estático privado createTeTime = "CreateToTime"; static final static private uploadDir = "uploadDir/"; / ** * Cambiar el nombre del archivo cargado * * @param nombre * @return */ private static string rename (name de cadena) {long Now = long.parselong (new SimpleDateFormat ("yyyymmddhhmmss") .Format (new Date ())); Largo aleatorio = (largo) (Math.random () * ahora); Cadena filename = ahora + "" + aleatory; if (name.IndexOf (".")! = -1) {FileName += name.substring (name.lastIndexOf (".")); } retorno de archivo de archivo; } / ** * nombre de archivo comprimido * * @param nombre * @return * / private static string zipname (name de cadena) {string prefix = ""; if (name.IndexOf (".")! = -1) {prefix = name.substring (0, name.lastIndexOf (".")); } else {prefijo = nombre; } return prefijo + ".zip"; } / ** * Sobre archivo * * @param solicitud * @param params * @param valores * @return * @throws excepción * / public static list <map <string, object >> upload (httpservletRequest request, string [] params, map <string, object []> valores) Lanza una excepción {list <map <string >> resultado = nueva arrayList <string <string, string, object (object) () lanza excepción {list <map <string, object >> resultado = new arrayList <map <string, string, object (object) () lanza excepción {list <map <string >> d. MultiparthttpservletRequest mrequest = (multipThttpServletRequest) solicitud; Map <string, multipartFile> fileMap = mrequest.getFilEmap (); String uploadDir = request.getSession (). Archivo archivo = nuevo archivo (uploadDir); if (! file.exists ()) {file.mkdir (); } Cadena filename = null; int i = 0; for (iterator <map.entry <string, multipartFile >> it = fileMap.Entryset () .Iterator (); it.hasNext (); i ++) {map.entry <string, multipartfile> entry = it.next (); Multipartfile mfile = entry.getValue (); filename = mfile.getOriginalFileName (); Cadena storename = renombre (nombre de archivo); Cadena nozipname = uploadDir + storeName; Cadena zipname = zipname (nozipname); // cargar para convertirse en un archivo comprimido ZipoutputStream OutputStream = new ZipOutputStream (new BufferedOutputStream (nuevo FileOutputStream (ZIPNAME))); outputStream.putNextEntry (new ZipEntry (nombre de archivo)); outputStream.setEncoding ("GBK"); FileCopyUtils.copy (mfile.getInputStream (), outputStream); Map <string, object> map = new HashMap <String, Object> (); // Valor de parámetro fijo Par de map.put (fileOperateUtil.RealName, ZipName (nombre de archivo)); map.put (fileopererutil.storename, zipname (storeName)); map.put (fileoperateUtil.size, nuevo archivo (zipname) .length ()); map.put (fileopererutil.suffix, "zip"); map.put (fileoperateUtil.ContentType, "Application/Octet-stream"); map.put (fileopererutil.createTime, nueva fecha ()); // Par de valor de parámetro personalizado para (String Param: Params) {map.put (param, valores.get (param) [i]); } resultado.Add (mapa); } resultado de retorno; } / ** * Descargar * @param solicitud * @param respuesta * @param storename * @param ContentType * @param RealName * @throws Exception * / public static void download (httpservletRequest solicitud, httpServletResponse respuesta, cadena storEnname, string contenttype, cadena real) lanza la excepción de excepción { respuesta.setContentType ("text/html; charset = utf-8"); request.setcharacterEncoding ("UTF-8"); BufferedinputStream bis = null; BufferedOutputStream bos = null; String ctxpath = request.getSession (). GetServletContext () .getRealPath ("/") + fileopererutil.uploaddir; String downloadPath = ctxpath + storeName; long filelength = nuevo archivo (downloadPath) .length (); respuesta.setContentType (contentType); respuesta.setheader ("Disposición de contenido", "Adjunto; FileName =" + New String (RealName.getBytes ("UTF-8"), "ISO8859-1")); respuesta.setheader ("content-longitud", string.valueOf (fileLength)); bis = new BufferedInputStream (nuevo FileInputStream (downloadPath)); bos = new BufferedOutputStream (respuesta.getOutputStream ()); byte [] buff = new Byte [2048]; int bytesread; while (-1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); } bis.close (); bos.close (); }} Se puede usar completamente sin cambiar la clase. Cabe señalar que el archivo cargado se coloca en WebContent/uploadDir.
(4) Agregue FileOperateController.java
/ ** * * @author geoin */ paquete com.geloin.spring.controller; import java.util.hashmap; import java.util.list; import java.util.map; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; importar org.springframework.stereotype.controller; importar org.springframework.web.bind.servletrequestutils; importar org.springframework.web.bind.annotation.requestMapping; importar org.springframework.web.servlet.modelandview; import com.geloin.spring.util.fileOpererutil; @Controller @RequestMapping (value = "Background/FileOperate") Class pública FileOperateController {/*** A la ubicación donde se cargue el archivo* @return*/@RequestMapping (value = "to_upload") public ModelandView toupload () {return y nuevo modelandview ("fondo/fileoperer/upload"); } / ** * Sobre archivo * * @param request * @return * @throws excepción * / @requestmapping (valor = "cargar") public modelandView upload (httpservletRequest request) lanza excepción {map <string, object> map = new HashMap <String, object> (); // string de alias [] alaises = servletRequestUtilss.getStringParameters (solicitud, "Alais"); String [] params = new String [] {"Alais"}; Map <string, object []> valores = new HashMap <String, Object []> (); valores.put ("alais", alaises); Lista <map <string, object >> dulte = fileOperateUtil.upload (solicitud, params, valores); map.put ("resultado", resultado); devolver nuevo ModelAndView ("Background/FileOperate/List", MAP); } / ** * Descargar * * @param Archivo * @Param Solicitud * @param Respuesta * @return * @throws Exception * / @RequestMapping (valor = "Descargar") Public ModelAndView Descargar (HttpservletRequest Solicitud, HttpServletResponse Response) Lanza {String StoreName = "2012050513403645108708708724.zip". Cadena realName = "Java Design Pattern.zip"; Cadena contentType = "aplicación/octet-stream"; Fileopererutil.download (solicitud, respuesta, storeName, contentType, realName); regresar nulo; }}Cambie el método de descarga usted mismo. Si usa la base de datos para guardar la información de archivo cargado, consulte la instancia de Spring MVC Integration MyBatis.
(5) Agregar fileoperate/upload.jsp
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8" PageEncoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> < 1.0 Transitional // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <foad> <meta http -equiv =" content-type "content =" text/html; <body> </body> <form enctype="multipart/form-data" action="<c:url value="/background/fileOperate/upload.html" />" method="post"> <input type="file" name="file1" /> <input type="text" name="alais" /><br /> <input type="file" name="file2" /> <input type="text" name = "alais" /> <br /> <input type = "file" name = "file3" /> <input type = "text" name = "alais" /> <br /> <input type = "subt" value = "upload" /> < /html>
Asegúrese de que el valor de cifrado sea multipart/formy-data; El valor del método es post.
(6) Agregar fileoperate/list.jsp
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8" PageEncoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> < 1.0 Transitional // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <foad> <meta http -equiv =" content-type "content =" text/html; <body> <c: foreach elementos = "$ {resultado}" var = "item"> <c: foreach elementos = "$ {elemento}" var = "m"> <c: if test = "$ {M.Key eq 'RealName'}"> $ {M.Value} </c: if> <Br/> </c: foreach> </c: foreach> </body> </htmll.(7) Acceda a la página de carga a través de http: // localhost: 8080/spring_test/fondos/fileoperate/to_upload.html, y descargue el archivo a través de http: // localhost: 8080/spring_test/fondos/fileoperer/descargar.html
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.