input type=”file”で画像アップロード前にプレビュー表示(jQuery)
2013年10月16日
一旦サーバーにアップロードしてから表示するのではなく、画像選択時にそのままブラウザにローカルのファイルを表示する方法をメモ程度に。
まずはhtml側。
<input type="file" id="file"> <img src="" id="preview" style="display:none;">
type=”file”なinputと、display:noneなimgタグを用意しておきます。
(imgタグは.afterとかで入れても良さそうですが・・)
そしてjs側。
$('#file').change(
function() {
if ( !this.files.length ) {
return;
}
var file = $(this).prop('files')[0];
var fr = new FileReader();
fr.onload = function() {
$('#preview').attr('src', fr.result ).css('display','inline');
}
fr.readAsDataURL(file);
}
);
#fileが変更されたら、imgタグにsrcを入れて、表示。
これを$(function(){ /*…*/ });とかに入れておけば動くと思います。