2
1

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.

GeekSalonAdvent Calendar 2023

Day 11

画像投稿のプレビュー表示してみた

Last updated at Posted at 2023-12-12

やること

Flaskで画像を投稿するときに、実際に投稿する前にプレビューでどんな画像が選択されているか表示する機能を作ります
Flaskでやってますが、実際の機能はHTMLだけで完結します

完成版

image.png
投稿する前にどんな画像が選択されているかを表示します

Github

実装

<h1 class="text-3xl font-bold mb-4">Image Upload and Preview</h1>

<form
  action="{{ url_for('upload') }}"
  method="post"
  enctype="multipart/form-data"
  id="upload-form"
  class="max-w-sm mx-auto bg-white p-6 rounded shadow-md"
>
  <input
    type="file"
    name="file"
    id="file-input"
    accept="image/*"
    onchange="previewImage()"
    class="mb-4 p-2 border border-gray-300 w-full"
  /><br />
  <img
    id="image-preview"
    src="#"
    alt="Image Preview"
    class="mb-4 w-full"
    hidden
  /><br />
  <button type="submit" class="bg-blue-500 text-white p-2 rounded">
    Upload
  </button>
</form>

<script>
  // プレビュー表示
  const previewImage = () => {
    const fileInput = document.getElementById("file-input");
    const imagePreview = document.getElementById("image-preview");

    if (fileInput.files && fileInput.files[0]) {
      const reader = new FileReader();
      reader.onload = (e) => (imagePreview.src = e.target.result);
      reader.readAsDataURL(fileInput.files[0]);
      imagePreview.hidden = false;
    }
  };
</script>

大事なのはscriptタグだけです
FileReaderで画像を受け取って用意しておいたimgタグにsrc設定して終わりです!

バイバイ〜〜〜

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?