0
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?

学習37日目

Posted at

内容

画像選択時のプレビュー機能の実装

前提

  • 画像投稿機能(active storage)を実装済
  • 画像は1枚のみ投稿
  • 追記部分以外の記述は省略

手順

画像のプレビューを表示させる部分を作る。
(今回はimage_previewというidに設定)
xxxx.html.erb

<div id = "image_preview"></div>

javascriptを記述する。
(別ファイルに切り出して書いてもOK)

xxxx.html.erb

<script>
    let imageInput = document.getElementById("district_image")
    let imagePreview  = document.getElementById("image_preview")
    imagePreview.setAttribute('style', 'width:150px; height:150px;');
    imageInput.addEventListener('change', (e) => {
        let file = e.target.files[0];
        let blob = window.URL.createObjectURL(file);
        let img = document.createElement('img');
        img.setAttribute('src', blob);
        imagePreview.appendChild(img);
    })
</script>

コメント

  • 様々なサイトを参考にしたが、自分の考える実装に合うものが無く、組み合わせて記述した。
  • active storageで保存されているデータについて知る必要があると感じた
0
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
0
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?