LoginSignup
11
8

More than 5 years have passed since last update.

vue.js-画像ファイルアップロード後の表示

Last updated at Posted at 2018-10-11

window上で選択したfileを表示する方法

Vue.jsを使うと簡単に選択したfileを表示することができたので、練習ながらまとめておく。

HTML

input要素(type="file")を使って行った。

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <link rel="stylesheet" href="style.css">
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    </head>
    <body>

        <div id="app">
            <input type="file" @change="change">
            <div v-if="preview">
                <img :src="preview">
            </div>
        </div>

        <script src="main.js"></script>
    </body>
</html>

Vue.js

dataは、previewとし、index.htmlのimg要素内のsrc属性に紐づけしておく。

main.js
var app = new Vue({
    el: '#app',
    data: {
        preview: ""
    },
    methods: {
        change: function(e){
            var file = e.target.files[0];
            if(file && file.type.match(/^image\/(png|jpeg)$/)){
                this.preview = URL.createObjectURL(file);
            }
        }
    }
});

main.js内のまとめ

  • input type="file"にはfilesというObjectがある。 そのfiles[0]に選択したファイルがObjectで入っている。 それを変数fileに格納する。
  • file.typeは、(image/png|jpeg)なので、正規表現を用いてmatch した場合のみ表示するようにする。
  • URL.createObjectURL(file)を用いる。 URL.createObjectURL()
  • データ、previewをバインドしているので、画像が表示される。
11
8
1

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
11
8