Spring MVC -Datei Upload und Download wie folgt:
(1) JAR-Pakete importieren: Ant.jar, Commons-fileUpload.jar, connom-io.jar.
(2) in SRC/Context/Dispatcher.xml hinzufügen
<bean id = "multipartresolver" p: defaultEnoding = "utf-8" />
Beachten Sie, dass Sie dem Kopf Inhalte hinzufügen müssen, wie unten nach dem Hinzufügen gezeigt:
<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://wwww.- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http:/www.springframe.org/Schema/context/bring-contework.org/Schema/-
(3) Fügen Sie die Tool Class FileoperateUtil.java hinzu
/ ** * * @Author Geoin */ package com.geloin.spring.util; import Java.io.BufferedInputStream; importieren java.io.bufferedOutputStream; Import Java.io.file; import Java.io.FileInputStream; importieren java.io.fileoutputStream; Java.Text.SimpledateFormat importieren; Import Java.util.ArrayList; import Java.util.date; import Java.util.hashMap; Import Java.util.iterator; importieren java.util.list; import Java.util.map; importieren javax.servlet.http.httpServletRequest; importieren javax.servlet.http.httpServletResponse; import org.apache.tools.zip.zipentry; import org.apache.tools.zip.zipoutputStream; import org.springframework.util.filecopyutils; import org.springframework.web.multipart.multipartFile; import org.springframework.web.multipart.multiparthttpServletRequest; public class FileoperateUtil {private statische endgültige Zeichenfolge Realname = "RealName"; private statische endgültige String -Storename = "Storename"; private statische endgültige String -Größe = "Größe"; private statische endgültige String -Suffix = "Suffix"; private statische endgültige String contentType = "contentType"; private statische endgültige String createTime = "CreateTime"; private statische endgültige String uploadDir = "UploadDir/"; / ** * Die hochgeladene Datei umbenennen * * @param name * @return */ private statische Zeichenfolge umbenennen (String -Name) {long now = long.parselong (new SimpledateFormat ("yyyymmmdhmmss") .Format (New Date ()); Long random = (lang) (math.random () * jetzt); String Dateiname = jetzt + "" + random; if (name.indexof (".")! } return Dateiname; } / ** * komprimierter Dateiname * * @param name * @return * / private statische String -ZipName (String -Name) {String prefix = ""; if (name.indexof (".")! } else {prefix = name; } return prefix + ".zip"; } / ** * Datei hochladen * * @param request * @param params * @param values * @return * @throws Exception * / public staticlist <map <String, Objekt >> Upload (httpServletRequest -Anforderung, String [] Params, Map <String, Objekt []> Werte) löst Ausnahme {map <map <map <map <map <String, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt, Objekt >>; MultiparthttpServletRequest mrequest = (multiparthttpServletRequest) Anfrage; Karte <String, MultipartFile> fileMap = mrequest.getFilemap (); String uploadDir = request.getSession (). GetServletContext () .GetRealPath ("/") + FileoperateUtil.Uploaddir; Datei Datei = neue Datei (UploadDir); if (! file.exists ()) {file.mkdir (); } String Dateiname = null; int i = 0; für (iterator <map.Entry <String, MultiPartFile >> it = fileMap.EntrySet () .Iterator (); it.hasnext (); i ++) {map.Entry <String, MultiPartFile> Eintrag = it.Next (); MultipartFile Mfile = Eintrag.GetValue (); fileName = mFile.getOriginalFileName (); String forename = umbename (Dateiname); String nozipName = UploadDir + Storename; String zipName = ZipName (NozipName); // hochladen, um ein komprimierter Datei -ZipoutputStream -Ausgangsstream = neuer ZipoutputStream (neuer BufferedOutputStream (neuer FileOutputStream (ZipName))) zu erhalten; outputStream.putNextEntry (neu Zipentry (Dateiname)); outputStream.setencoding ("gbk"); FilecopyUtils.copy (mFile.getInputStream (), outputStream); Karte <String, Objekt> map = new HashMap <String, Object> (); // Parameterwertpaar map.put (FileoperateUtil.RealName, ZipName (Dateiname)); map.put (FileOperateUtil.Storename, ZipName (Storename)); map.put (FileOperateUtil.Size, neue Datei (ZipName) .Length ()); map.put (FileoperateUtil.suffix, "Zip"); map.put (FileoperateUtil.ContentType, "Anwendung/Oktett-Stream"); map.put (FileoperateUtil.CreateTime, New Date ()); // benutzerdefinierte Parameterwertpaar für (Zeichenfolge Params: Params) {map.put (param, values.get (param) [i]); } result.add (map); } Rückgabeergebnis; } / ** * Download * @param request * @param antwort * @param forename * @param contentType * @param Realname * @throws Exception * / public static void download (httpServletRequest -Anfrage, httpServletResponus, String StorEname, String ContentType, String Realname) Wurst {{{{{{{{{{{ Antwort.SetContentType ("text/html; charSet = utf-8"); request.setcharactercoding ("utf-8"); BufferedInputStream Bis = null; BufferedOutputStream bos = null; String ctxpath = request.getSession (). GetServletContext () .GetRealPath ("/") + FileoperateUtil.Uploaddir; String DownloadPath = CtxPath + Storename; long filelength = neue Datei (DownloadPath) .Length (); response.setContentType (contentType); response.setheader ("Inhaltsdisposition", "Anhang; Dateiname =" + neue String (RealName.getBytes ("UTF-8"), "ISO8859-1"); response.setheader ("Inhaltslänge", String.Valueof (FileLength)); Bis = neuer BufferedInputStream (neuer FileInputStream (DownloadPath)); bos = new bufferedOutputStream (response.getOutputStream ()); Byte [] Buff = New Byte [2048]; int bytesread; while (-1! } Bis.close (); bos.close (); }} Es kann vollständig verwendet werden, ohne die Klasse zu ändern. Es ist zu beachten, dass die hochgeladene Datei unter WebContent/UploadDir platziert ist.
(4) FileoperateController.java hinzufügen
/ ** * * @Author Geoin */ package com.geloin.spring.controller; import Java.util.hashMap; importieren java.util.list; import Java.util.map; importieren javax.servlet.http.httpServletRequest; importieren javax.servlet.http.httpServletResponse; import org.springframework.stereotype.controller; import org.springframework.web.bind.servletRequestutils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelandView; import com.geloin.spring.util.FileoperateUtil; @Controller @RequestMapping (value = "Hintergrund/Fileoperate") public class FileoperateController {/*** zu dem Ort, an dem die Datei hochgeladen wird } / ** * Datei hochladen * * @param request * @return * @throws Exception * / @RequestMapping (value = "Upload") public modelAndView Upload (httpServletRequest -Anforderung) löst Ausnahme aus {map <String, Objekt> map = new Hashmap <string, Objekt> (); // alias String [] alaises = ServletRequestUtils.getStringParameters (Anfrage, "Alais"); String [] params = new String [] {"alais"}; Karte <string, Object []> values = new HashMap <String, Object []> (); Werte.put ("Alais", Alaise); Liste <map <String, Objekt >> result = FileoperateUtil.Upload (Anforderung, Parameter, Werte); map.put ("Ergebnis", Ergebnis); Neue ModelAndView zurückgeben ("Hintergrund/Fileoperate/List", Karte); } /** * Download* * @param attachment * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "download") public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception { String storeName = "201205051340364510870879724.zip"; String Realname = "Java Design Muster.zip"; String contentType = "Anwendung/Oktett-Stream"; DateioperateUtil.Download (Anfrage, Antwort, Storename, ContentType, RealName); null zurückkehren; }}Bitte ändern Sie die Download -Methode selbst. Wenn Sie die Datenbank verwenden, um die hochgeladenen Dateiinformationen zu speichern, lesen Sie bitte die myBatis -Instanz der Spring MVC -Integration.
(5) Fileoperate/Upload.jsp
<%@ page Language = "java" contentType = "text/html; charset = utf-8" pageCoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! 1.0 Übergang // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <head> <meta http-äquiv =" content-type "content =" texus> texus> html; <body> < /body> <form engType = "multiPart /form-data" action = "<c: url value =" /background /fileoperat /upload name = "alais" /> <br /> <Eingabe type = "Datei" name = "file3" /> <Eingabe type = "text" name = "alais" /> <br /> <Eingabe type = "subly" value = "upload" /> < /form> < /html>>
Stellen Sie sicher, dass der EngType-Wert mehrteiler/Formdaten ist. Der Methodenwert ist post.
(6) Fileoperate/list.jsp
<%@ page Language = "java" contentType = "text/html; charset = utf-8" pageCoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! 1.0 Übergang // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <head> <meta http-äquiv =" content-type "content =" texus> texus> html; <body> <c: foreach items = "$ {result}" var = "item"> <c: foreach items = "$ {item}" var = "m"> <c: if test = "$ {m.key eq 'realName'}"> $ {m.value} </c: if> </c: Foreach> </C.(7) Greifen Sie auf die Upload -Seite über http: // localhost: 8080/spring_test/background/fileoperate/to_Upload.html zu und laden Sie die Datei über http: // localhost: 8080/spring_test/background/fileoperate/download.html herunter.html
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.