1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBootによる画像アップロード機能を作成する際の注意点

Posted at

ポイント

  • Spring Security の設定を見直す
  • ResourceHandler の設定をする

参考

上記のサイトを参考に説明します。
英語で書かれたページですが、やってる事はそのままです

ポイント1 ) Spring Security の設定を見直す

これは以下サイトでも触れているのですが、なかなかわかりにくい点になります。

認証にはspring securityを使用しておりあすので、WebSecurityConfigurerAdapter内で認証から除外する必要があります。これを行わないと、フォルダにアクセスができません。

   @Override
   public void configure(WebSecurity web) >throws Exception {
       >web.ignoring().antMatchers("/favicon.ico", >"/css/**", "/js/**", "/images/**",
               "/fonts/**","/upload/**");
   }

images配下のデータへのアクセスを許可する記述です。
参考サイトでも述べられているように、セキュリティの関係で必要になります。

ポイント2 ) ResourceHandler の設定をする

アップロードされたファイルを含むディレクトリを公開し、クライアント(ウェブブラウザ)がアクセスできるようにする必要があります。以下のようなコードで設定ファイルを作成します。(*本文訳)

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       exposeDirectory("user-photos", registry);
   }
    
   private void exposeDirectory(String dirName, ResourceHandlerRegistry registry) {
       Path uploadDir = Paths.get(dirName);
       String uploadPath = uploadDir.toFile().getAbsolutePath();
        
       if (dirName.startsWith("../")) dirName = dirName.replace("../", "");
        
       registry.addResourceHandler("/" + dirName + "/**").addResourceLocations("file:/"+ >uploadPath + "/");
   }

ResorceHandolerはSpring フレームワークが静的リソースをクライアントに提供するためのSpringフレームワークのクラスです。
→ ドキュメント : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.html

addResourceHandler() によって静的リソースの読み込みのためのパスを追加します。

最後に

画像表示に関しての設定は、日本語記事では解決方法がなかなか見つからず非常に苦労しました。

不明点や、 深掘りして欲しい点がありましたらコメントをいただけますと幸いです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?