Spring MVC Arquivo Upload e download, o seguinte:
(1) Importar pacotes de jar: Ant.Jar, Commons-FileUpload.jar, Connom-io.jar.
(2) Adicione SRC/Context/Dispatcher.xml
<bean id = "multipartresolver" p: defaultEncoding = "utf-8" />
Observe que você precisa adicionar conteúdo à cabeça, como mostrado abaixo, depois de adicionar:
<Beans default-lazy-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.xsd http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
(3) Adicione a classe da ferramenta FileOperateTil.java
/ ** * * @author geoin */ package com.geloin.spring.util; importar java.io.bufferInputStream; importar java.io.bufferedOutputStream; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.text.simpledateFormat; importar java.util.arraylist; importar java.util.date; importar java.util.hashmap; importar java.util.iterator; importar java.util.list; importar java.util.map; importar javax.servlet.http.httpServletRequest; importar 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; classe pública fileoPerateUtil {private static final string realname = "realname"; String final estática privada string storename = "storename"; String final estática privada tamanho = "tamanho"; private estático final string sufix = "sufixo"; String final estática privada contentType = "contentType"; String final estática privada CreateTime = "CreateTime"; String final estática privada uploaddir = "uploaddir/"; / ** * Renomeie o arquivo carregado * * @param nome * @return */ string estática privada renomear (nome da string) {long now = long.parselong (new SimpleDateFormat ("yyyymmddhhmmss") .format (new Date ()); Longo aleatório = (longo) (math.random () * agora); String filename = agora + "" + aleatório; if (name.indexOf (".")! = -1) {nome do arquivo += name.substring (name.lastIndexof (".")); } retornar o nome do arquivo; } / ** * Nome do arquivo compactado * * Nome @param * @return * / private static string zipName (nome da string) {string prefix = ""; if (name.indexOf (".")! = -1) {prefix = name.substring (0, name.LastIndexOf ("."); } else {prefix = name; } retornar prefixo + ".zip"; } / ** * FILHO DE ALGUNA * * @PARAM Solicitação * @param params * @param valores * @return * @throws exceção * / list estática pública <map <string, objeto >> upload (httpServletRequest solicitação, string [] params, map <, objeto []> valores) lança a exceção {list <pp <string, objeto>> MultiparthttpServletRequest mRequest = (multiparthttpServletRequest) solicitação; Mapa <string, multipartfile> filemap = mrequest.getFilemap (); String uploaddir = request.getSession (). GetServletContext () .getRealPath ("/") + fileoPerateUtil.uploaddir; Arquivo de arquivo = novo arquivo (uploaddir); if (! file.exists ()) {file.mkdir (); } String filename = null; int i = 0; for (iterator <pap.entry <string, multipartfile >> it = filemap.entrySet () .iterator (); it.hasnext (); i ++) {map.entry <string, multipartfile> entrada = it.next (); MultipartFile mFile = Entry.getValue (); nome do arquivo = mfile.getoriginalfilename (); String storename = renomear (nome do arquivo); String nozipname = uploaddir + storename; String zipName = zipName (NozipName); // upload para se tornar um arquivo compactado zipOutputStream outputStream = new ZipOutputStream (new BufferOutputStream (new FileOutputStream (zipName)); outputStream.putNextEntry (novo zipentry (nome do arquivo)); outputStream.SetEncoding ("GBK"); FileCopyUtils.copy (mfile.getInputStream (), outputStream); Mapa <string, object> map = new hashmap <string, object> (); // fixo parâmetro value par map.put (FILEOPERATETIL.REALNAME, ZIPNAME (nome do arquivo)); map.put (FILEOPERATETIL.STORENAME, ZIPNAME (Storename)); map.put (FILEOPERATETIL.SIZE, NOVO FILE (zipName) .Length ()); map.put (fileoPerateUtil.suffix, "zip"); map.put (FILEOPERATETIL.COntentType, "Application/Octet-Stream"); map.put (FILEOPERATETIL.CREATETIME, new Date ()); // par de valor de parâmetro personalizado para (String param: params) {map.put (param, valores.get (param) [i]); } resultado.add (mapa); } resultado de retorno; } / ** * Download * @param request * @param Resposta * @param storename * @param contentType * @param realname * @throws Exception * / public static void Download (httpServleTrequest Solicy, httpServLetResponse, String Storename, string contenttype, string realname) Response.setContentType ("Texto/html; charset = utf-8"); request.setcharacterencoding ("UTF-8"); BufferInputStream bis = null; BufferOutputStream bos = nulo; String ctxpath = request.getSession (). GetServletContext () .getRealPath ("/") + fileoPerateUtil.uploaddir; String DownloadPath = CTXPath + Storename; long fileleLength = novo arquivo (DownloadPath) .Length (); Response.setContentType (contentType); Response.setheader ("Content-Disposition", "Applement; filename =" + new String (realname.getBytes ("UTF-8"), "ISO8859-1")); Response.setheader ("Length-comprimento", String.ValueOf (FILELENGLE)); bis = new bufferInputStream (new FileInputStream (DownloadPath)); bos = new bufferoudOutputStream (Response.getOutputStream ()); byte [] buff = novo byte [2048]; int bytesread; while (-1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); } bis.close (); bos.close (); }} Pode ser usado completamente sem alterar a classe. Deve -se notar que o arquivo carregado é colocado no webcontent/uploaddir.
(4) Adicione FileOperatEController.java
/ ** * * @author geoin */ package com.geloin.spring.controller; importar java.util.hashmap; importar java.util.list; importar java.util.map; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importar org.springframework.tereotype.controller; importar org.springframework.web.bind.servletrequestutils; importar org.springframework.web.bind.annotation.requestmapping; importar org.springframework.web.servlet.modelandView; importar com.geloin.spring.util.fileoperateUtil; @Controller @ReQuestMapping (Value = "Antecedentes/FileOperate") Public class FileOperatECOntroller {/*** para o local em que o arquivo é carregado* @return*/@requestMapping (value = "to_upload") public ModelAndview TouPload () {Return ModelAndView ("Bordado de Bordado") } / ** * Arquivo de upload * * @param request * @return * @throws Exception * / @RequestMapping (value = "upload") public ModelAndView upload (httpServletRequest Solicy) lança exceção {map <string, object> map = new hashmap <string, object> (); // Alias String [] ALAISES = servletRequestutils.getStringParameters (Solicitação, "Alais"); String [] params = new String [] {"Alais"}; Mapa <string, object []> valores = new hashmap <string, objeto []> (); valores.put ("Alais", Alaises); List <map <string, object >> resultado = FILEOPERATETIL.UPLOAD (solicitação, params, valores); map.put ("resultado", resultado); retornar novo ModelAndView ("Background/FileOperate/List", mapa); } / ** * Download * * Anexo @param * @param request * @param Resposta * @return * @throws Exceção * / @RequestMapping (value = "Download") public ModelAndView Download (httpServleTrequest Solicy, httpServLePSOPSOnse) String realname = "Java Design Pattern.zip"; String contentType = "Application/Octet-Stream"; FILEOPERATEUTIL.DOWNLOAD (Solicitação, Resposta, Storename, ContentType, Realname); retornar nulo; }}Altere você mesmo o método de download. Se você usar o banco de dados para salvar as informações do arquivo enviado, consulte a instância MyBatis Integration Mybatis da Spring MVC.
(5) Adicione FileOperate/upload.jsp
<%@ página linguagem = "java" contentType = "text/html; charset = utf-8" pageEncoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jstl/core" http://java.sun.com/jstl/core "/! 1.0 Transition // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <head> <meta http-equiv =" content-tty "/"/"text/html; <Body> < /body> <form rype = "multipart /form-data" action = "<c: url value =" /background /fileoPerate /upload.html " />" method = "post"> <input type = "file" name = "file1" /> <type = "" name "" alais " /> <br /" <r /"" type = "text" name = "Alais" /> <br /> <input type = "file" name = "file3" /> <input type = "text" name = "alais" /> <r /> <input type = "submit" value = "upload" /> < /form> < /html>
Verifique se o valor do ENCTYPE é multipart/formulário; O valor do método é post.
(6) Adicione FileOperate/list.jsp
<%@ página linguagem = "java" contentType = "text/html; charset = utf-8" pageEncoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jstl/core" http://java.sun.com/jstl/core "/! 1.0 Transition // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <head> <meta http-equiv =" content-tty "/"/"text/html; <Body> <c: foreach itens = "$ {resultado}" var = "item"> <c: foreach itens = "$ {item}" var = "m"> <c: if test = "$ {M.Key eq 'realname'}"> $ {M.Value}(7) Acesse a página de upload através de http: // localhost: 8080/spring_test/background/fileoperate/to_upload.html e faça o download do arquivo por http: // lochost: 8080/spring_test/background/fileoperado/download.html
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.