Spring MVC 파일 업로드 및 다운로드 : 다음과 같이.
(1) JAR 패키지 가져 오기 : Ant.jar, Commons-FileUpload.jar, Connom-Io.jar.
(2) src/context/dispatcher.xml을 추가하십시오
<bean id = "multipartresolver"p : defaultEncoding = "utf-8" />
추가 후 아래 그림과 같이 머리에 콘텐츠를 추가해야합니다.
<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://wwww.spramfffram work.org. 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) 도구 클래스 FileOperateUtil.java를 추가하십시오
/ ** * * @author geoin */ package 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; java.util.arraylist 가져 오기; import java.util.date; java.util.hashmap import; import java.util.iterator; Java.util.list 가져 오기; java.util.map import; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.tools.zip.zipentry; import org.apache.tools.zip.zipoutputstream; org.springframework.util.filecopyutils import; org.springframework.web.multipart.multipartfile; org.springframework.web.multipart.multiparthttpservletrequest; public class fileOperateUtil {private static final String realName = "realName"; 개인 정적 최종 문자열 storename = "StoreName"; 개인 정적 최종 문자열 크기 = "크기"; 개인 정적 최종 문자열 접미사 = "접미사"; 개인 정적 최종 문자열 contentType = "ContentType"; 개인 정적 최종 문자열 createTime = "CreateTime"; 비공개 정적 최종 문자열 업로드 디르 = "uploaddir/"; / ** * 업로드 된 파일의 이름을 바꿉니다 * @param name * @return */ private static string rename (String name) {long now = long.parselong (new simpledateformat ( "yyyyymmddhhmms") .format (new Date ())); long random = (long) (math.random () * 지금); 문자열 filename = now + "" + random; if (name.indexof ( ".")! = -1) {filename += name.substring (name.lastIndexof ( ".")); } 리턴 파일 이름; } / ** * 압축 파일 이름 * * @param name * @return * / private static String Zipamam (문자열 이름) {String prefix = ""; if (name.indexof ( ".")! = -1) {prefix = name.substring (0, name.lastindexof ( ".")); } else {prefix = 이름; } return prefix + ".zip"; } / ** * 파일 업로드 * * @param params * @param params * @param value * @return * @throws 예외 * / public static list <map <string, object >> upload (httpservletrequest request, string, map <string, object []> value) {list <map <string, object >> result = new arraylist = new Arraylist multiparthttpservletrequest mrequest = (multiparthttpservletrequest) 요청; map <string, multipartfile> filemap = mrequest.getfilemap (); 문자열 uploadDir = requestSession (). getServletContext () .getRealPath ( "/") + fileOperateUtil.uploaddir; 파일 = 새 파일 (uploaddir); if (! file.exists ()) {file.mkdir (); } 문자열 filename = null; int i = 0; for (iterator <map.entry <string, multipartfile >> it = filemap.entryset () .iterator (); hasnext (); i ++) {map.entry <string, multipartfile> enther = it.next (); multipartFile mfile = Entry.GetValue (); filename = mfile.getoriginalfilename (); String Storename = Rename (Filename); 문자열 nozipname = uploaddir + storeName; 문자열 zipname = zipname (nozipname); // 압축 파일이되기 위해 업로드 ZipOutputStream outputStream = new ZipoutPutStream (새 bufferedOutputStream (new FileoutPutStream (ZipName))); outputStream.putNextEntry (New Zipentry (filename)); outputStream.setencoding ( "gbk"); filecopyutils.copy (mfile.getInputStream (), outputStream); map <string, object> map = new Hashmap <String, Object> (); // 수정 된 매개 변수 값 쌍 맵 .put (FileOperateUtil.RealName, ZipName (filename)); map.put (FileOperateUtil.storename, Zipname (storename)); map.put (FileOperateUtil.Size, 새 파일 (ZipName) .length ()); map.put (FileOperateUtil.suffix, "zip"); map.put (FileOperateUtil.ContentType, "Application/Octet-stream"); map.put (fileOperateUtil.CreatEtime, new Date ()); // (문자열 param : params)에 대한 사용자 정의 매개 변수 값 쌍 {map.put (param, value.get [i]); } result.add (지도); } 반환 결과; } / ** * 다운로드 * @param request * @param response * @param storename * @param contenttype * @param realname * / public static void download (httpservletrequest request, httpservletrepsonse 응답, 문자열 storename, 문자열 contenttype, string realname) 추력 예외 { Response.setContentType ( "Text/Html; charset = utf-8"); request.setcharacterencoding ( "UTF-8"); bufferedInputStream bis = null; BufferedOutputStream BOS = NULL; 문자열 ctxpath = request.getSession (). getServletContext () .getRealPath ( "/") + fileOperateUtil.uploaddir; 문자열 downloadpath = ctxpath + storeName; long filelength = 새 파일 (downloadPath) .length (); Response.SetContentType (ContentType); response.setHeader ( "Content-Disposition", "첨부 파일; filename =" + new String (realName.getBytes ( "UTF-8"), "iso8859-1")); response.setHeader ( "컨텐츠 길이", String.Valueof (filelength)); bis = new bufferedInputStream (new FileInputStream (downloadPath)); bos = new bufferedOutputStream (response.getOutputStream ()); 바이트 [] buff = 새로운 바이트 [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 import; Java.util.list 가져 오기; java.util.map import; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; org.springframework.stereotyp.controller import; import org.springframework.web.bind.servletrequestutils; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.servlet.modelandview import; import com.geloin.spring.util.fileoperateUtil; @Controller @RequestMapping (value = "background/fileOperate") 공개 클래스 파일 파일 OPERATECONTROLLER {/*** 파일이 업로드되는 위치에* @return*/@RequestMapping (value = "to_upload") public modelandview toupload () {return new ModelAndView ( "background/fileperate/upload"); } / ** * 파일 업로드 * * @param request * @return * @throws Exception * / @requestmapping (value = "ubload") public modelandview ubload (httpservletrequest request) 예외 {map <string, object> map = new Hashmap <String, Object> (); // 별칭 문자열 [] alaises = servletRequestUtils.getStringParameters (요청, "alais"); 문자열 [] params = new String [] { "alais"}; map <string, object []> value = new Hashmap <string, Object []> (); values.put ( "alais", alaises); list <map <string, object >> result = fileOperateUtil.upload (요청, 매개 변수, 값); map.put ( "결과", 결과); 새로운 ModelAndView ( "Background/FileOperate/List", MAP)를 반환합니다. } / ** * 다운로드 * * @param 첨부 * @param request * @param response * @return * @throws Exception * / @requestmapping (value = "download") public model 및 download (httpservletrequest request, httpservletresponse responsk) 예외 {string storename = "2012051340364510870924.zip"; 문자열 realName = "Java Design Pattern.zip"; 문자열 contentType = "Application/Octet-stream"; FileOperateUtil.Download (요청, 응답, StoreName, ContentType, RealName); 널 리턴; }}다운로드 방법을 직접 변경하십시오. 업로드 된 파일 정보를 저장하기 위해 데이터베이스를 사용하는 경우 Spring MVC Integration MyBatis 인스턴스를 참조하십시오.
(5) FileOperate/upload.jsp를 추가하십시오
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib prefix = "c"uri = "http://java.sun.com/jsp/jstl/core"%> <! 1.0 전환 // 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 =" /backgring /fileOperate /upload.html " />"method = "post"> <input type = "file"name = "file1" /> <input type = "text"name = "alais" /> <input type = "file "2"2 " />. 이름 = "alais" /> <br /> <input type = "file"name = "file3" /> <input type = "text"name = "alais" /<br /> <input type = "value ="upload " /> < /form> < /html>
ENCTYPE 값이 멀티 파트/형태-데이터인지 확인하십시오. 메소드 값은 POST입니다.
(6) fileOperate/list.jsp를 추가하십시오
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib prefix = "c"uri = "http://java.sun.com/jsp/jstl/core"%> <! 1.0 전환 // 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 items = "$ {item}"var = "m"> <c : if test = "$ {m.key eq 'realName'}"> $ {m.value} </c : if> <br/> </c : foreach> </html> </html>(7) http : // localhost : 8080/spring_test/backgring/fileOperate/to_upload.html을 통해 업로드 페이지에 액세스하고 http : // localhost : 8080/spring_test/background/file -operate/download.html을 통해 파일을 다운로드하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.