Загрузка и загрузка файла Spring MVC следующим образом:
(1) Импортные пакеты JAR: Ant.Jar, Commons-FileUpload.jar, Connom-Io.jar.
(2) Добавить в src/context/dispatcher.xml
<bean id = "multiartresolver" p: defaultendencoding = "utf-8" />
Обратите внимание, что вам нужно добавить контент в голову, как показано ниже после добавления:
<Боевые по умолчанию 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.sprame.sprame.sprame.sprame.sprmemema/xmlns: mvccememe. xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.spramework.org/schema/mvcema/mvcema/mvcema http://www.spramework.org/schema. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context/spring-3.0.xsd ">
(3) Добавить класс инструмента FileOperatil.java
/ ** * * @author geoin */ package com.geloin.spring.util; Импорт java.io.bufferedinputstream; Импорт java.io.bufferedOutputStream; Импорт java.io.file; импортировать java.io.fileinputstream; Импорт java.io.fileOutputStream; импортировать java.text.simpledateformat; импортировать java.util.arraylist; импортировать java.util.date; импортировать java.util.hashmap; импортировать java.util.iterator; импортировать java.util.list; импортировать java.util.map; Импорт javax.servlet.http.httpservletrequest; Импорт javax.servlet.http.httpservletresponse; Импорт org.apache.tools.zip.zipentry; Импорт org.apache.tools.zip.zipoutputstream; Импорт org.springframework.util.filecopyutils; Импорт org.springframework.web.multipart.multipartfile; Импорт org.springframework.web.multipart.multiparthttpservletrequest; открытый класс FileOperatiL {Private Static Final String realName = "realName"; частная статическая конечная строка Storename = "Storename"; частная статическая конечная строка size = "size"; частная статическая конечная строка суффикс = "Суффикс"; частная статическая конечная строка contentType = "contentType"; частная статическая финальная строка createTime = "createTime"; Private Static Final String uploadDir = "uploadDir/"; / ** * Переименование загруженного файла * * @param name * @return */ private static String rename (string name) {long now = long.parselong (new SimpleDateFormat ("yyyyMmddhhmmss") .format (new Date ())); Long random = (long) (math.random () * Теперь); String fileName = теперь + "" + random; if (name.indexof (".")! = -1) {filename += name.substring (name.lastindexof (".")); } вернуть имя файла; } / **! if (name.indexof (".")! = -1) {prefix = name.substring (0, name.lastindexof (".")); } else {prefix = name; } вернуть префикс + ".zip"; } /** * Upload file* * @param request * @param params * @param values * @return * @throws Exception */ public static List<Map<String, Object>> upload(HttpServletRequest request, String[] params, Map<String, Object[]> values) throws Exception { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); Multiparthttpservletrequest mrequest = (MultiparthttpservletRequest) запрос; Map <string, multiplectfile> fileMap = mrequest.getFileMap (); String uploadDir = request.getSession (). GetServletContext () .getRealPath ("/") + fileOperateLitil.uploadDir; File file = new File (uploadDir); if (! file.exists ()) {file.mkdir (); } String filename = null; int i = 0; for (iterator <map.entry <string, multiplactfile >> it = fileMap.EntrySet () .iterator (); it.hasnext (); i ++) {map.Entry <string, multiplaRtfile> entry = it.next (); Multiplackfile mfile = entry.getValue (); filename = mfile.getoriginalfilename (); String Storename = rename (filename); String nozipName = uploadDir + storename; String ZipName = ZipName (nozipName); // загрузка, чтобы стать сжатым файлом ZipoutputStream outputStream = new ZipOutputStream (New BufferedOutputStream (New FileOutputStream (ZipName))); outputStream.putNextEntry (новый Zipentry (имя файла)); outputStream.SetEncoding ("GBK"); Filecopyutils.copy (mfile.getInputStream (), outputStream); Map <string, object> map = new hashmap <string, object> (); // Исправлено значение значения параметра PARP.PUT (FileOperatiL.RealName, ZipName (FileName)); map.put (fileoperateil.storename, zipname (Storename)); map.put (fileoperateil.size, новый файл (ZipName) .length ()); map.put (fileoperatiL.suffix, "Zip"); map.put (fileoperateut.contenttype, "Приложение/октет-поток"); map.put (fileoperateil.createtime, new Date ()); // Пользовательское значение значения параметра для (String param: params) {map.put (param, values.get (param) [i]); } result.add (map); } return Result; } / ** * Скачать * @param request * @param response * @param StoreName * @param contentType * @param RealName * @Throws Exception * / public Static void Download (httpservletRequest, httpservletrespons response.setContentType ("text/html; charset = utf-8"); request.setcharacterencoding ("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; String ctxpath = request.getSession (). GetServletContext () .getRealPath ("/") + fileoPerateil.UploadDir; String downloadpath = ctxpath + storename; long fileLength = новый файл (downloadPath) .length (); response.setContentType (ContentType); response.setheader ("content-disposition", "Attachment; filename =" + new String (realName.getBytes ("utf-8"), "iso8859-1")); response.setheader ("content-dength", string.valueof (filelength)); bis = new BufferedInputStream (New FileInputStream (DownloadPath)); bos = new BufferedOutputStream (response.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 (); }} Его можно полностью использовать, не изменяя класс. Следует отметить, что загруженный файл размещен в WebContent/uploadDir.
(4) Добавить fileOperateController.java
/ ** * * @author geoin */ package com.geloin.spring.controller; импортировать java.util.hashmap; импортировать java.util.list; импортировать java.util.map; Импорт javax.servlet.http.httpservletrequest; Импорт javax.servlet.http.httpservletresponse; Import org.springframework.sterotype.controller; Импорт org.springframework.web.bind.servletrequestutils; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.servlet.modelandView; импорт com.geloin.spring.util.fileoperateutil; @Controller @Requestmapping (value = "founale/fileoperation") открытый класс FileOperateController {/*** в местоположение, где загружается файл* @return*/@requestmapping (value = "to_upload") public modelandView toupload () {return new modelandview ("founale/fileopart/upload"); } / ** * upload file * * @param request * @return * @throhs excection * / @requestmapping (value = "upload") public model и upload (httpservletrequest) throws exception {map <string, object> map = new hashmap <string, object> (); // псевдоним string [] alaises = servletrequestutils.getstringparameters (запрос, "alais"); String [] params = new String [] {"alais"}; Map <string, object []> values = new HashMap <String, Object []> (); values.put ("alais", alaises); Список <map <string, object >> result = fileOperateUtil.upload (request, params, values); map.put («результат», результат); вернуть New ModelAndView ("founale/fileoPerate/List", MAP); } / ** * Скачать * * @param вложение * @param запрос * @param response * @return * @throws exception * / @requestmapping (value = "download") public modelandview скачать (httpservletrequest, httpservletresponse response) execult {string storeName = "20120505134036457087087087087087084.1108708. String realName = "java design pattern.zip"; String contentType = "Приложение/Octet-Stream"; FileoperateUtil.download (запрос, ответ, Storename, ContentType, realName); вернуть ноль; }}Пожалуйста, измените метод загрузки самостоятельно. Если вы используете базу данных для сохранения загруженной информации о файле, пожалуйста, обратитесь к экземпляру Mybatis Integration Spring MVC.
(5) Добавить файлопературу/upload.jsp
<%@ page language = "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! Doctype html pupirn " 1.0 Transitional // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <Head> <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 = "Отправить" value = "upload" /> < /form> < /html>
Убедитесь, что значение Enctype составляет Multipart/Form-Data; Значение метода - пост.
(6) Добавить файлопературу/list.jsp
<%@ page language = "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! Doctype html pupirn " 1.0 Transitional // en "" http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd "> <html> <Head> <meta http-equiv =" Content-Type "content =" text/html; <body> <c: foreach items = "$ {result}" var = "item"> <c: foreach elects = "$ {item}" var = "m"> <c: if test = "$ {m.key eq 'realname'}"> $ {m.value} </c: if> <br/> </c: for peach> </cfeeach> </ht> </ht> </ht> </ht> </ht> </HT> </HT> </HT> </HT> </HT> </HT> </ht.(7) Доступ к странице загрузки через http: // localhost: 8080/spring_test/founale/fileoperate/to_upload.html и загрузите файл через http: // localhost: 8080/spring_test/founale/fileoperate/download.html
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.