LoginSignup
0
0

inputタグの画像サンプルを表示する方法

Posted at

問題

Laravelで画像を下記のinputでアップロードするときに
保存前にプレビューを表示させたい

<input type="file">

方法

コード

profileEdit.blade.php
<section class="container">
    <h2 class="mt-5 text-center">プロフィール画像更新</h2>
    <div class="form-group">
        <label for="id">↓下をクリックして画像をアップロードしてください</label><br>
        <input type="file" id="input">
        <div class="profile-picture profile-picture-border mt-3">
            <img id="sample" class="img-fluid">
        </div>
    </div>
    <button class="btn btn-danger">アップロード</button>
</section>
app.js
// 画像サンプル表示
// 1. ファイル選択後に呼ばれるイベント
$("#input").on("change", function (e) {
  // 2. 画像ファイルの読み込みクラス
  var reader = new FileReader();
  // 3. 準備が終わったら、id=sample1のsrc属性に選択した画像ファイルの情報を設定
  reader.onload = function (e) {
      $("#sample").attr("src", e.target.result);
  }
  // 4. 読み込んだ画像ファイルをURLに変換
  reader.readAsDataURL(e.target.files[0]);
});
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