最近、私の同僚は、テクノロジーに関する電子書籍があるかどうか尋ねました。私は自分のコンピューターで小さなライブラリを開きましたが、電子メールは彼を送るには大きすぎて、会社はフォルダーとの共有を禁止していたので、小さなファイルアップロードプログラムを書いてLinuxマシンに展開するのを半日費やしました。
機能を提供する: 1。ファイルアップロード2。ファイルリスト表示とダウンロード
元のアップロードされたピースは醜いです。私はそれを最適化するためにいくつかのJSコードを書きました。最終的なインターフェイスは次のように表示されます。
最初に結果を与え、以下でそれらを段階的に実装する方法を示します。
1.新しいプロジェクトを作成します
最初のことは、新しいスプリングブートプロジェクトを作成することです。 Webサイトでプロジェクトを初期化するか、IDEのSpring Initial Functionを使用することを選択して、新しいプロジェクトを作成できます。ここでは、アイデアから新しいプロジェクトを作成します。
次に、グループとアーティファクトを入力し、[次へ]をクリックし続けます。
この時点で、このモジュール選択インターフェイスが表示されます。 Webオプションをクリックして、Webをチェックして、これがWebAppであることを証明してください。次に、テンプレートエンジンをクリックして、フロントエンドテンプレートエンジンを選択します。 Thymleafを選択します。 Spring-Bootの役人は、JSPの代わりにこのテンプレートを使用することも推奨しています。
最後のステップで、プロジェクトが正常に初期化されるのを待ちます。
2.POM設定
まず、プロジェクトに追加する必要がある依存関係を確認し、POMファイルを直接投稿してください。
<?xml version = "1.0" encoding = "utf-8"?> <project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance <http://www.w3.org/2001 xsi:schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.0.sdsd"> <modeleversion> 4.0.0 </modelversion> <groupid> shuqing28 <バージョン> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> upload </name> <description> spring boot </description> <parent> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter- </artifactid>リポジトリからのlookup parent-> </parent> <properties> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <project.reporting.outputencoding> utf-8 </project.reporting.outputencoding> <Dependency> groupId> org.springframework.boot </groupid> <artifactid> spring-boot-starter </artifactid> </dependency> <dependency> springframework.boot </groupid> <artifactid> spring-boot-starter-thyleaf </artifactid> </artifactid> </artifactid> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-configuration-processor </artifactid> <optional> true </optional> </dependency> <sependency> <ependency> <groupid> </dependency> <! - https://mvnrepository.com/artifact/org.webjars/bootstrap-> <dependency> <groupid> org.webjars </groupid> <artifactid> bootstrap </artifactid> <バージョン> 3.3.5 </バージョンhttps://mvnrepository.com/artifact/org.webjars.bower/jquery-> <dependency> <groupid> org.webjars.bower </groupid> <artifactid> jquery </artifactid> <バージョン> 2.2.4 </version> <gripid> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> </plugin> </plugins> </build> </project>
Spring-Boot-Starter-ThymeleafにはWebAppが含まれており、最後の2つのWebJars Integrate BootstrapとJQueryが含まれており、その他のコードが使用されます。
最後のスプリングブートMavenプラグインは、システムの作成時に追加され、次の利点があります。
1. ClassPathの下ですべての瓶をパッケージ化し、ユーザーがサービスを転送するように容易にする実行可能ファイル「über-jar」を構築できます。
2。public static void main()メソッドを自動的に検索し、実行可能クラスとしてマークします
3。Spring-Bootバージョンによると、組み込みの依存関係の説明が提供されます。
3。ファイルコントローラーをアップロードします
SpringMVCを使用してファイルをアップロードしている場合は、MultiPartresolver Beanを構成するか、web.xmlでa <multipart-config>を構成する必要がありますが、Spring-Bootの自動構成の助けを借りて、何もする必要はありません。コントローラークラスを直接書き込むために、SRC/Main/Javaの下に新しいコントローラーパッケージを作成し、新しいFileuploAdControllerを作成します。
パッケージcom.shuqing28.upload.controller; import com.shuqing28.uploadfiles.pojo.linker; Import com.shuqing28.uploadfiles.exceptions.storagefilenotfoundexception; Import com.shuqing28.uploadfiles.Service.StorageerseRage org.springframework.beans.factory.annotation.autowired; Import org.springframework.core.io.resource; Import org.springframework.htttpheaders; Import org.springframework.http.responsentity; org.springframework.ui.model; import org.springframework.web.bind.annotation。*; import org.springframework.web.multipart.multipartfile; Import org.springframework.web.servlet.mvc.methat.notation.annotation.mturicomponentsbuilder springframework.web.servlet.mvc.support.redirectattributes; Import java.io.ioexception; Import java.util.list; Import java.util.stream.collectors; @controllollerpublic class fileuploadcontroller {private final storegeervice storeages; @autowired public fileuploadcontroller(storageservice storageservice){this.storageservice = storageservice; } @getMapping( "/")public string listuploadedfiles(モデルモデル)IoException {list <linker> linkers = storageservice.loadall()。 path.getFileName()。toString())。build()。toString()、path.getFileName()。toString())).collect(collectors.tolist()); model.addattribute( "linkers"、linkers); "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(); }}@Controllerアノテーションはクラスの定義で追加され、これがコントローラーであることを証明します。各メソッドは、@getMappingと@PostMappingがそれぞれ取得および投稿リクエストに対応して追加されます。
まず、@getMapping( "/")、メソッドlistuploadedfiles、名前が示すように、ファイルリストが表示されます。ここでは、StorageServiceを使用してフォルダー内のすべてのファイルをトラバースし、マップメソッドを使用してリンクとファイル名リストを合成して、リンカーオブジェクトの配列を返します。リンカーオブジェクトは、次の2つの部分のみを含む単純なpojoです。
private string fileurl; private string filename;
この方法には、Java8でのストリームの使用が含まれます。わからない場合は、Java8機能に関するこの記事を詳細に読むことができます(II)ストリームAPI。
次は@GetMapping("/files/{filename:.+}")であり、ファイルのダウンロード機能を提供するservefile、またはstorageserviceを使用し、storageserviceコードが後で投稿されます。最後に、ResponseNtityを使用して、ファイルをボディとしてリクエストパーティに返します。
@PostMapping("/")のHandleFileuploadは、POSTリクエストを使用してファイルをアップロードします。パラメーター@RequestParam( "ファイル")は、Webページリクエストでファイルオブジェクトを抽出するか、Storageserviceを使用してオブジェクトを保存し、リダイレクトを使用してWebページを更新し、アップロードされたメッセージを正常に提供します。
4。ファイル処理
上記のコントローラーで呼ばれる多くの方法は、Storageserviceによって提供されています。次の方法を含むインターフェイスを定義します。
パッケージcom.shuqing28.uploadfiles.service; Import org.springframework.core.io.resource; Import org.springframework.web.multipart.multipartfile; Import java.nio.file.path; Import Java.util.stream.Stream; Public Interface SporeageService {); void store(multipartfileファイル); Stream <Path> loadall();パスロード(String Filename); Resource LoadAsResource(String Filename); void deleteall();}ローカルファイルシステムを使用してファイルの長期的なダウンロードを処理しているだけなので、次の実装クラスがあります。
パッケージcom.shuqing28.uploadfiles.service; import com.shuqing28.uploadfiles.exceptions.storageexception; Import com.shuqing28.uploadfiles.exceptions.storageFileNotFoundexception; org.springframework.beans.factory.annotation.autowired; Import org.springframework.core.io.resource; Import org.springframework.core.io.urresource; Import org.springframework.stereototy.service; Import org.sprameframework springframework.util.stringutils; import org.springframework.web.multipart.multipartfile; Import java.ioexception; Import java.net.malformedurlexception; inmolied java.nio.file.file.files; import java.file. java.nio.file.paths; Import java.nio.file.standardcopyoption; Import java.util.stream.stream; @servicepublic class filesystemstorageervice explence storageservice {プライベートパスルートロケーション; @autowired public filesystemSystemstorageService(storemingproperties Properties){this.RootLocation = paths.get(properties.getLocation()); } @Override public void init(){try {files.createdirectories(rootlocation); } catch(ioException e){new StorageExceptionをスロー( "ストレージを初期化できませんでした"、e); }} @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); }} @Override public stream <ath> loadall(){try {return files.walk(this.rootlocation、1).filter(path->!path.equals(this.rootlocation)).map(path-> this.Rootlocation.RELATIVIZE(PATH)); } catch(ioException e){new StorageExceptionをスロー(「保存されたファイルを読み取らなかった」、e); }} @Overrideパブリックパスロード(string filename){return rootlocation.resolve(filename); } @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); }} @Override public void deleteall(){filesystemutils.deleterecively(rootlocation.tofile()); }}また、このクラスは基本的にJavaのNIOを使用し、パスオブジェクトを使用して、ファイルの場所のデフォルト保存パスを定義します。
最初にストアメソッドを見てみましょう。ストアは、マルチパートファイルオブジェクトをパラメーターとして受け入れます。従来のJSPと比較して、バイナリバイト配列を通過するだけです。 MultiPartFileは、アップロードされたファイルに関するさまざまな情報を取得できるように、呼び出すための多くの便利な方法を提供します。
パブリックインターフェイスMultiPartFileは、inputstreamSource {string getName();文字列getoriginalfilename(); string getContentType(); boolean isempty(); long getsize(); byte [] getBytes()はioExceptionをスローします。 inputstream getInputStream()はiOExceptionをスローします。 void transfoto(file dest)はioexception、IllegalStateException;}をスローします;}コードは、ファイルコピーメソッドを使用して、ファイルストリームを場所に対応するパスにコピーします。もちろん、転送メソッドを使用して、ファイルfile.transferTo(this.rootLocation.resolve(filename).toFile());
Loadallメソッドは、このパスのすべてのファイルパス情報をロードし、LoadAsResourceはファイルをリソースオブジェクトとしてロードし、コントローラーコードを調べ、最後にリクエスト担当者に戻るボディとしてリソースオブジェクトを受け入れます。
5。フロントエンドテンプレート
最後に、フロントエンドテンプレートが定義されています。ここでは、最初にコードを調べます。
<html xmlns:th = "http://www.thymeleaf.org"> <head> <title>共有ファイル</title> </head> <body> <body> <body> <body> <h2 th:h2 th:text = "$ {message}"/>> </div> <div> <div> <div> <post "/"/" enctype = "multipart/form-data"> <! - component start-> <input type = "file" name "file" style = "visibility; height; height; height:0"/> <div name = "fichier1"> <input "placeholder = 'file ... - > <div> <ボタンタイプ= "submit">送信</button> <ボタンタイプ= "reset"> reset </button> </div> </form> </div> <ul> <li th:equire = "linker:$ {linkers}"> <a th:href = "$ {linker.fileurl}" Th:text = "$ {linker.filename}"/> </li> </ul> </div> <script src = "// ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.1.min.js"></script> <script src = "/webjars/bootstrap/3.3.5/js/bootstrap.min.js"> </script> <スクリプトタイプ= "text/javascript" th:inline = "javascript"> function bs_input_file(){){$( "。入力ファイル")。 {var Element = $( "。入力-Ghost"); $( "button.btn-reset")。 {$( '。入力ファイル')。 } $(function(){bs_input_file();}); </script> <link rel = "styleSheet" href = "/webjars/bootstrap/3.3.5/css/bootstrap.min.css" rel = "external nofollow"/>> </body> </html>ここで重要なことは、<form>タグのコンテンツです。 <form method = "post" action = "/" enctype = "multipart/form-data"> enctypeは、multipart/form-dataとして記述する必要があります。投稿を使用してファイルをアップロードします。元のアップロードコントロールは醜いので、テキスト+入力を作成して表面に配置し、以下に見えないアップロードファイル入力を配置しました。あなたは自分でコードを見ることができるので、私はこの記事でそれについて話しません。
ここでは、ファイルリストを表示するリストも配置します。ここでは、サーバーが提供するリンカーオブジェクトを取得します。常にforeachすることで、FileURLとFilenameに2つの要素を取得できます。
ここでは、jQueryがMicrosoftのCDNに置き換えられており、Webjarsを導入できないため、その理由はわかりません。
その他の設定
src/main/resources/application.propertiesでアップロードファイルサイズ制限を設定します
spring.http.multipart.max-file-size = 128mbspring.http.multipart.max-request-size = 128mb
さらに、デフォルトのファイル保存パスも設定されています。
パッケージcom.shuqing28.uploadfiles.config; Import org.springframework.boot.context.properties.configurationProperties; @configurationProperties; @configurationProperties( "Storage")Public Class StorageProperties {private string location = "/home/jenkins/upload-files/"; public string getLocation(){return location; } public void setlocation(string location){this.location = location; }}ここでは、StorageProperties設定のため、アプリケーションクラスに追加する必要があることに注意してください。
@enableconfigurationProperties annotation@springbootapplication@enableconfigurationProperties(storeadproperties.class)public class uploadapplication {public static void main(string [] args){springApplication.run(uploadapplication.class、args); }}要約します
上記は、ファイルのアップロードとダウンロード機能を実現するために編集者が紹介したSpring Boot + Thymeleafです。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!