LoginSignup
10
11

More than 5 years have passed since last update.

フォームで選択された画像をその場でプレビュー

Last updated at Posted at 2013-10-27
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Example</title>
</head>
<body>
<img id="picture">
<form>
<input type="file" name="image" accept="image/jpeg,image/png">
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/holder/2.0/holder.js"></script>
<script>
$(function(){
    $('input[name="image"]').on('change', function(e){
        //  multiple指定はしてないので1個だけ入ってくるはず
        var f = e.target.files[0];
        console.log(f);
        if (f.type.match('image.*')){
            //  Reader生成
            var reader = new FileReader();
            //  Readerのロード完了時のハンドラ
            reader.onload = (function(){
                //  この時点でreader.resultにはファイルがdataURL化された文字列が入る
                $('img#picture').attr('src', reader.result);
            });
            //  dataURL形式で読み込み
            reader.readAsDataURL(f);
        }
    });
});
</script>

</body>
</html>
10
11
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
10
11