이 기사는 SpringBoot의 업로드 및 다운로드 기능을 소개합니다.
1. SpringBoot 프로젝트를 만들고 종속성을 추가하십시오
컴파일 ( "org.springframework.boot : spring-boot-starter-web") compile ( "org.springframework.boot : spring-boot-starter-thymeleaf")
프로젝트 디렉토리는 다음과 같습니다.
Application.java 스타트 업 클래스
패키지 안녕하세요; org.springframework.boot.springApplication import; org.springframework.boot.autoconfigure.springbootapplication import; org.springframework.boot.context.properties.enableconfigurationProperties; @SpringBootApplication Public Class Application {public static void main (String [] args) {springApplication.run (application.class, args); }}2. 테스트 페이지를 만듭니다
리소스/템플릿 디렉토리에서 새 uploadform.html을 만듭니다
<html xmlns : th = "http://www.thymeleaf.org"> <body> <div th : if = "$ {message}"> <h2 th : text = "$ {message}"/> </div> <form 메소드 = "multype ="multipart/form-data "action ="/"> 업로드 : </td> <td> <입력 유형 = "파일"이름 = "file"/> </td> </tr> <tr> <td> <td> <td> <입력 유형 = "value ="value = "upload"/> </td> </tr> </table> </form> <liv> <ul> <li th : $ {files : et. Th : href = "$ {file}"rel = "external nofollow"th : text = "$ {file}"/> </li> </ul> </div> </body> </html>3. 새로운 StoragesService 서비스를 만듭니다
StorageService 인터페이스
포장 Hello.Storage; import org.springframework.core.io.resource; org.springframework.web.multipart.multipartfile; java.nio.file.path 가져 오기; java.util.stream.stream import; 공개 인터페이스 StoragesErvice {void init (); void store (multipartfile 파일); stream <aTH> loadAll (); 경로로드 (String filename); Resource LoadAsResource (String filename); void deleteall (); }StorageService 구현
포장 Hello.Storage; import org.springframework.core.io.resource; org.springframework.core.io.urlresource; org.springframework.stereotyp.service; org.springframework.util.filesystemutils import; org.springframework.util.stringutils import; org.springframework.web.multipart.multipartfile; import java.io.ioexception; java.net.malformedurlexception import; import java.nio.file.files; java.nio.file.path 가져 오기; java.nio.file.paths import; java.nio.file.StandardCopyOption 가져 오기; java.util.function.predicate import; java.util.stream.stream import; @service public class filesystemstorageservice emplements storageservice {private final path rootlocation = paths.get ( "upload-dir"); / *** 파일 저장** @param 파일 파일*/ @override public void store (multipartFile 파일) {String filename = StringUtils.cleanPath (file.getoriginalFilename ()); try {if (file.isempty ()) {Throw New StorageException ( "빈 파일을 저장 실패" + filename); } if (filename.contains ( "..")) {// 보안 검사 새 스토리지 exception ( "현재 디렉토리 외부에 상대 경로가있는 파일을 저장할 수 없습니다" + filename); } files.copy (file.getInputStream (), this.RootLocation.Resolve (filename), StandardCopyOption.Replace_Existing); } catch (ioException e) {새 StorageException 던지기 ( "파일 저장 실패" + filename, e); }} /*** upload -dir* @return* /@override public stream <aThO> loadAll () {retry {return files.walk (this.rootlocation, 1) // path.fat.equals (this.rootlocation) .filter (new Presticate <path> () {@overrided public boolean test (path) path) }); } catch (ioexception e) {새 스토리지 exception ( "저장된 파일을 읽지 못했다", e); }} @override public path load (String filename) {return rootlocation.resolve (filename); } / *** 파일 리소스 가져 오기* @param filename 파일 이름* @return resource* / @override public resource loadAsResource (String filename) {try {path file = load (filename); Resource Resource = New UrlResource (file.touri ()); if (resource.exists () || resource.isreadable ()) {return resource; } else {새 StorageFilenotFoundException ( "파일을 읽을 수 없음 :" + filename); }} catch (marformedurlexception e) {새 StorageFilenotFoundException ( "파일을 읽을 수 없습니다 :" + filename, e); }} / *** 업로드 디렉토리에서 모든 파일 삭제* / @override public void deleteall () {filesystemutils.deletereCursivel (rootlocation.tofile ()); } / *** 초기화* / @override public void init () {try {files.createdirectories (rootlocation); } catch (ioException e) {새 StorageException 던지기 ( "스토리지 초기화 할 수 없음", e); }}}StorageException.java
포장 Hello.Storage; Public Class StorageException 확장 runtimeexception {public StorageException (문자열 메시지) {super (메시지); } public StorageException (문자열 메시지, 던질 가능한 원인) {super (메시지, 원인); }} StorageFilenotFoundException.javapackage hello.storage; 공개 클래스 StorageFilenOtFoundException 확장 스토리지 exception {public storageFilenotFoundException (문자열 메시지) {super (메시지); } public StorageFilenotFoundException (문자열 메시지, 던질 가능한 원인) {super (메시지, 원인); }}4. 컨트롤러 생성
업로드 된 파일을 프로젝트의 업로드 DIR 디렉토리에 넣고 기본적으로 인터페이스에 다운로드 가능한 파일을 나열하십시오.
listuploadedFiles 함수는 현재 디렉토리에 모든 파일을 나열합니다.
Servile 다운로드 파일
handleFileUpload 파일을 업로드합니다
패키지 안녕하세요; import java.io.ioexception; Java.util.stream.collectors 가져 오기; org.springframework.beans.factory.annotation.autowired; import org.springframework.core.io.resource; org.springframework.http.httpheaders; org.springframework.http.respontentity import; org.springframework.stereotyp.controller import; import org.springframework.ui.model; org.springframework.web.bind.annotation.exceptionhandler import; org.springframework.web.bind.annotation.getMapping; import org.springframework.web.bind.annotation.pathvariable; org.springframework.web.bind.annotation.postmapping; org.springframework.web.bind.annotation.requestparam; org.springframework.web.bind.annotation.responsebody; org.springframework.web.multipart.multipartfile; org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilder; org.springframework.web.servlet.mvc.support.redirectattributes; hello.storage.storageFilenotFoundException 가져 오기; hello.storage.storageservice 가져 오기; @Controller public class fileUploadController {private final storagesErgice StoragesErvice; @autowired public fileUploadController (StoragesErgice StoragesErgice) {this.StoragesErvice = StoragesErvice; } @getMapping ( "/") public String listuploadedFiles (모델 모델)는 ioException {model.addattribute ( "files", storagesErgice.loadall (). map (path-> mvcuricomponentsBuilder.frommethodName (fileUploadcontroller.class, "servfile", path.getFilename (). toString ()). build (). toString ()) .collect (collectors.tolist ()); "uploadform"을 반환합니다. } @getMapping ( "/files/{filename :.+}") @ResponseBody public responseentity <Reporce> servfile (@PathVariable String filename) {resource file = storageService.loadAsource (filename); return responseNity.ok (). 헤더 (httpheaders.content_disposition, "첨부 파일; filename =/" " + file.getfilename () +"/"".body(file); } @postmapping ( "/") public String handleFileUpload (@requestparam ( "file") multipartfile 파일, RedirectAttributes redirectattributes) {storageservice.store (파일); REDIRECTATTRIBUTES.ADDFLASHATTRIBUTE ( "Message", "귀하는 성공적으로" + file.getoriginalFilename () + "!"); "리디렉션 :/"를 반환합니다. } @ExceptionHandler (StorageFilenotFoundException.class) public response entity <?> handlestorageFilenotFound (StorageFilenotFoundException exc) {return responsenity.notfound (). build (); }} 소스 코드 다운로드 : https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
요약
위의 것은 편집기가 소개 한 SpringBoot 파일을 업로드하고 다운로드하기위한 소스 코드입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!