この記事では、スプリングブートのアップロードおよびダウンロード機能を紹介します。
1.スプリングブートプロジェクトを作成し、依存関係を追加します
コンパイル( "org.springframework.boot:spring-boot-starter-web")compile( "org.springframework.boot:spring-boot-starter-thymeleaf")
プロジェクトディレクトリは次のとおりです。
Application.Javaスタートアップクラス
パッケージこんにちは。 Import 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: "$ {message}"/> </div> <div> <form method = "post" enctype = "multipart/form-data"アップロード:</td> <td> <入力タイプ= "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "submit" value = "upload"/> </td> </tr> </table> </form> </div> <> <> <> <ul < Th:href = "$ {file}" rel = "external nofollow" th:text = "$ {file}"/> </li> </ul> </div> </body> </html>3.新しいStorageserviceサービスを作成します
Storageserviceインターフェイス
パッケージhello.storage; Import org.springframework.core.io.resource; Import org.springframework.web.multipart.multipartfile; java.nio.file.pathをインポートします。 java.util.stream.streamをインポートします。 public interface storageservice {void init(); void store(multipartfileファイル); Stream <Path> loadall();パスロード(String Filename); Resource LoadAsResource(String Filename); void deleteall(); }Storageserviceの実装
パッケージhello.storage; Import org.springframework.core.io.resource; Import org.springframework.core.io.urlresource; org.springframework.stereotype.serviceをインポートします。 org.springframework.util.filesystemutilsをインポートします。 org.springframework.util.stringutilsをインポートします。 Import org.springframework.web.multipart.multipartfile; java.io.ioexceptionをインポートします。 java.net.malformedurlexceptionをインポートします。 java.nio.file.filesをインポートします。 java.nio.file.pathをインポートします。 java.nio.file.pathsをインポートします。 java.nio.file.standardcopyoptionをインポートします。 java.util.function.predicateをインポートします。 java.util.stream.streamをインポートします。 @Service public class FilesystemStystemStorageServiceはStorageservice {private final Path rootlocation = paths.get( "upload-dir"); / ***ファイルを保存** @paramファイル*/ @Override public void store(multipartfile file){string filename = stringutils.cleanpath(file.getoriginalFileName()); try {if(file.isempty()){throw new StorageException( "空のfile" + filename); } if(filename.contains( "..")){//これはセキュリティチェックスローnew StorageException( "現在のディレクトリの外側に相対パスでファイルを保存できない" + filename); } files.copy(file.getInputStream()、this.rootlocation.resolve(filename)、StandardCopyoption.Replace_Existing); } catch(ioException e){new StorageException( "ファイルの保存に失敗した" + filename、e); }} /***下のすべてのファイルをリストしますupload -dir* @return* /@override public stream <path> loadall(){return files.walk(this.rootlocation、1)// path->!path.equals(this.rootlocation).filter(new Predicate <Path>(){@Override public path.() }); } catch(ioException e){new StorageExceptionをスロー(「保存されたファイルを読み取らなかった」、e); }} @Overrideパブリックパスロード(string filename){return rootlocation.resolve(filename); } / ***ファイルリソースを取得* @param filenameファイル名* @return resource* / @override public resource loadasresource(string filename){try {path file = load(filename);リソースリソース= new UrlResource(file.touri()); if(resource.exists()|| resource.isreadable()){return resource; } else {throw new StorageFileNotFoundException( "ファイルを読み取れなかった:" + filename); }} catch(malformedurlexception e){new StorageFileNotFoundExceptionをスロー( "ファイル:" + filename、e); }} / *** upload-dirディレクトリ内のすべてのファイルを削除* / @override public void deleteall(){filesystemutils.deleterecively(rootlocation.tofile()); } / ***初期化* / @Override public void init(){try {files.createdirectories(rootlocation); } catch(ioException e){new StorageExceptionをスロー( "ストレージを初期化できませんでした"、e); }}}StorageException.java
パッケージhello.storage; Public Class StorageExceptionはruntimeExceptionを拡張します{public StorageException(string message){super(message); } public StorageException(Stringメッセージ、スロー可能な原因){super(message、cause); }} StorageFileNotFoundException.javapackage hello.storage; Public Class StorageFileNotFoundExceptionは、StorageExceptionを拡張します{public StorageFileNotFoundException(String Message){super(message); } public StorageFileNotFoundException(Stringメッセージ、スロー可能な原因){super(message、cause); }}4。コントローラーの作成
アップロードされたファイルをプロジェクトのアップロードDIRディレクトリに配置し、デフォルトでインターフェイス上のダウンロード可能なファイルをリストします。
listuploadedfiles関数は、現在のディレクトリのすべてのファイルをリストします
servefileダウンロードファイル
HandleFileuploadアップロードファイル
パッケージこんにちは。 java.io.ioexceptionをインポートします。 java.util.stream.collectorsをインポートします。 Import org.springframework.beans.factory.annotation.autowired; Import org.springframework.core.io.resource; Import org.springframework.http.httpheaders; org.springframework.http.responseentityをインポートします。 org.springframework.stereotype.controllerをインポートします。 Import org.springframework.ui.model; org.springframework.web.bind.annotation.exceptionhandlerをインポートします。 Import org.springframework.web.bind.annotation.getMapping; org.springframework.web.bind.annotation.pathvariableをインポートします。 Import org.springframework.web.bind.annotation.postmapping; Import org.springframework.web.bind.annotation.RequestParam; Import org.springframework.web.bind.annotation.responsebody; Import org.springframework.web.multipart.multipartfile; Import org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsBuilder; Import org.springframework.web.servlet.mvc.support.redirectattributes; hello.storage.storagefilenotfoundexceptionをインポートします。 hello.storage.storageserviceをインポートします。 @controller public class fileuploadcontroller {private final storageservice storageservice; @autowired public fileuploadcontroller(storageservice storageservice){this.storageservice = storageservice; } @getMapping( "/")public string listuploadedfiles(モデルモデル)throws ioexception {model.addattribute( "files"、storageservice.loadall()。 path.getFileName()。toString())。build()。toString()).collect(collectors.tolist())); "uploadform"を返します。 } @getMapping( "/files/{filename:。+}")@responsebody public ResponseNtity <sesource> servefile( @pathvariable string filename){resource file = storageservice.loageSresource(filename); RESPONSEENTENTITY.ok()。header(httpheaders.content_disposition、 "attachment; filename =/" " + file.getFileName() +" /").body(file); } @PostMapping( "/")public string handlefileupload(@requestparam( "file")multipartfile file、redirectattributes redirectattributes){storageservice.store(file); redirectattributes.addflashattribute( "message"、 "" + file.getoriginalfilename() + "!"); "redirect:/"を返します。 } @exceptionHandler(StorageFileNotFoundException.Class)Public ResponseNtity <?> HandLestorageFileNotFound(storageFileNotFoundException ec){return ResponseNtity.notfound()。build(); }}ソースコードのダウンロード:https://github.com/hellokittynii/springboot/tree/master/springbootuploadanddownload
要約します
上記は、エディターが紹介したスプリングブートファイルをアップロードおよびダウンロードするためのソースコードです。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!