파일 업로드 및 다운로드 기능은 최근 프로젝트에서 사용되었습니다. 이 기능이 더 중요하다고 생각하므로 특별히 추출하여 직접 시도했습니다.
다음은 참조를 위해 SpringMVC 구성 환경에서 파일을 업로드하고 다운로드하는 특정 단계입니다. 특정 내용은 다음과 같습니다
1. 기본 구성 :
Maven 가져 오기 패키지 및 구성 pom.xml. SpringMVC의 기본 종속성 외에도 파일을 업로드 할 때 사용하는 Commons-IO.jsr 및 Commons-FileUpload.jar를 가져와야합니다.
<project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xsi : schemalocation = "http://maven.apache.org/pom/0.0.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> filloadtest </groupid> <artifactid> filloadtest </artifactid> <packaging> war </packaging> <name> <samshot> webapp </name> <url> http://maven.apache.org </url> <cledame> finalname> filloadtest </finalname> <flugins> <!- 다음 구성은 강제 업데이트가있을 때마다 JRE 버전이 변경되지 않도록 할 수 있습니다. 이것을 설정하지 않으면 JRE는 강제 업데이트가 강요 될 때마다 1.5로 다시 변경됩니다-> <flugin> <ArtifactID> Maven-Compiler-Plugin </artifactid> <bersion> 2.3.2 </version> <cound> 1.7 </source> <garget> 1.7 </target> <coding> verf-8 <comoding> encoding> encoding> <bootclasspath> $ {java.home} /lib/rt.jar </bootclasspath> </compilerarguments> </configuration> </plugin> </build> <pectionaly> <pectionency> <groupid> junit </groupid> <artifactid> junit </arepactid> 3.8.1 <pectionency> <groupid> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> <버전> 4.0.6. release </version> </dependency> <groupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-annotations </artifactid> 2.2 </의존성> <pectionency> <groupId> com.fasterXml.jackson.core </groupId> <artifactID> Jackson-Core </artifactid> <version> 2.2.3 </version> </dependency> <groupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-databind> 2.2. </의존성> <pectionency> <groupId> Commons-FileUpload </groupId> <artifactID> Commons-FileUpload </artifactid> <version> 1.3.1 </version> </fectionency> <pectionement> <groupId> Commons-IO </groupId> <artifactID> </expendencies> 2.4 </version> 2.4 </version> </version> 2.4 </version>Web.xml의 기본 구성 :
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://java.sun.com/xml/ns/javaee" xmlns : web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id ="webapp_id "version ="2.5 "> <filter> <description> charset 필터 </descript> <filter-name> encodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <description> charset encoding </description> <param-name> 인코딩 </param-name> <apar-value> utf-8 </param-value> </filter> <filter> <filter-name> encodingFilter </filter-name> <Url-pattern>/*</url-pattern> </filter-mapping> <servlet-name> springmvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispitcherservlet </servlet class> <Param-Name> ContextConfigLocation </param-name> <param-value> classpath : spring.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> springmvc </servlet-name> <Url-pattern>* <colling-file> index.html </welcome-file> <welcome-file> index.htm.htm </welcome-file> <welcome-file> index.jsp </welcome-file> <welcome-file> index.jsp </welcome-file> <welcome-file> default.html </welcome-file> <welcome-file> default.htm </welcome-file> </welcome-file-list> </web-app>
스프링 기본 구성 Spring.xml :
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframwork.org/schema/mvc.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/contet http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvvc/sprger-mvc.xsd <Context : Annotation-Config /> <MVC : Annotation-Driven /> <Context : Component-Scan Base-Package = "Controllers" /> <!-IE가 ajax를 실행할 때 JSON으로 돌아 오는 것을 피하기 위해 파일 다운로드를 피하기 위해-> <bean id = "mappingjacksonhttpmessageconver"> <property name "> list <renst> <value> text/html; charset = utf-8 </value> </list> </property> </bean> <!-스프링 MVC 주석 기능을 요청하고 주석의 매핑을 완료하기 위해 pojos-> <ean> <property name = "messageconvers"> <list> <ref bean = "mappingjacksonhttpmessagegegeconver"/>>>>>>>>>>>>>>>>>>>>>>>>>>>>>들 때요. </list> </property> </bean> <!-파일 업로드 지원-> <bean id = "multipartresolver"> <!-100m-> <속성 이름 = "maxuploadsize"value = "104857600"> </property> <속성 이름 = "defaultencoding"value = "utf-8"> </bean> </beans>
2. 파일 업로드 코드
업로드 된 간단한 페이지 index.html의 경우 양식 양식을 제출할 때 Entype의 설정에주의를 기울이십시오.
<! docType html> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"/> </head> <body> <body action = "./ uploadfile.do"method = "post"encType = "" "" "" "" "" "" "" "" "" "" "" " <입력 유형 = "제출"값 = "제출"/> </form> </body> </html>
해당 배경 Java 코드를 업로드하십시오. 구체적인 질문은 의견을 참조하십시오.
패키지 컨트롤러; import java.io.file; import java.io.ioexception; import java.util.iterator; import javax.servlet.http.httpservletrequest; import org.apache.commons.io.fileutils; org.springframework.http.httpheaders; import org.springframework.http.httpstatus; import org.springframework.http.mediatype; org.springframework.http.respontentity import; org.springframework.stereotyp.controller import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestmethod; org.springframework.web.bind.annotation.requestparam; org.springframework.web.multipart.multipartfile; org.springframework.web.multipart.multiparthttpservletrequest; org.springframework.web.multipart.commons.commonsmultipartresolver; @controller public class filecontroller { /** * 파일 업로드 * * @author : tuzongxun * @title : uploadfile * @param @param @param request * @param @throws 불법 행위 * @param @throws ioexception * @return apr 28, 2016, 2016 1:222222222222222222222222222222222228. @requestmapping (value = "/uploadfile.do", method = requestmethod.post) public void uploadfile (httpservletrequest request)는 불법 행정 exception, ioexception {// @requestparam ( "file") multipartfile, multipartresolver = 새로운 commontmultipartresolver request.getSession (). getServletContext ()); // 요청에 파일 업로드가 있는지 확인합니다. // 요청 iterator <string> iter = multirequest.getFilenames ()에서 모든 파일 이름을 가져옵니다. while (iter.hasnext ()) {// 업로드 된 파일 get multipartfile f = multirequest.getfile (iter.next ()); if (f! = null) {// 현재 업로드 된 파일의 파일 이름을 가져옵니다. string myfilename = f.getoriginalFilename (); // 이름이 ""가 아닌 경우 파일이 존재한다는 것을 의미합니다. 그렇지 않으면 (myfilename.trim ()! = "" ") {// path String path ="c : // users // tuzongxun123 // desktop // " + myfilename; 파일 로컬 파일 = 새 파일 (Path); f.transferto (localfile); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}제출할 파일을 선택하면 선택한 파일이 코드의 지정된 위치로 전달되는 것을 볼 수 있습니다. 페이지 렌더링은 다음과 같습니다
3. 파일 다운로드
파일 다운로드에는 다운로드 된 파일의 저장 경로가 필요합니다. 이것은 수동으로 채워졌습니다. 특정 프로젝트에있는 경우 데이터베이스에 파일 이름과 업로드 된 스토리지 경로를 저장할 수 있습니다. 그런 다음 파일 목록의 페이지를 추가하여 파일 이름과 파일 경로를 표시 한 다음 클릭하여 해당 파일 이름과 경로를 다운로드 할 때 배경 작업에 업로드하십시오.
/ ** * 파일 다운로드, 파일 이름 및 파일 주소 필요 * * @Author : tuzongxun * @title : 다운로드 * @param @param @param @param @param @param @param @param @param @param @param @param @rows ioexception * @returnresponseentity <byte []> * @date apr 28,2016 1:21:32 pm * @Throws */ @requestmapp. "/downloadfile.do") public responseentity <byte []> download (@requestparam ( "name") 문자열 이름, @requestparam ( "filepath") String Path)는 ioexception {file file = new File (path); httpheaders 헤더 = 새로운 httpheaders (); String filename = new String (name.getBytes ( "UTF-8"), "ISO-8859-1"); // garbled 중국어 이름 헤드러의 문제를 해결하기 위해. headers.setContentType (mediaType.Application_octet_stream); 새로운 응답 entity <byte []> (fileUtils.ReadFileTobyTeArray (파일), 헤더, httpstatus.created); } HTML 페이지는 파일 이름과 파일 경로를 간단하게 채우고 양식 양식을 사용하여 배경에 제출하는 것입니다. 그런 다음 배경은 페이지에 파일 경로 팝업을 저장하기 위해 선택 상자에 대한 응답을 제어합니다. 물론, 나는 여기서 배경에서 아무것도하지 않았다. 파일이 존재하지 않으면 오류 가보고됩니다. 해당 처리를 수행 할 수 있습니다.
파일 다운로드 :
</br> </br> <form action = "./ downloadfile.do"style = "테두리 : 1px 단단한 회색; 너비 : 자동;" 메소드 = "post"> 파일 이름 : <input type = "text"name = "name"/> </br> </br> 파일 경로 : <input type = "text"name = "filepath"/> </br> </br> <입력 유형 = "value ="value = "다운로드 확인"/> </form>
페이지보기는 다음과 같습니다.
파일이 존재하지 않으면 오류는 다음과 같습니다.
위의 내용은이 기사에 관한 모든 것입니다. 모든 사람의 학습에 도움이되기를 바랍니다.