デモはこちら
編集:必要に応じてアップロードされたファイルを削除するボタンを追加しました。表示/非表示の効果が気に入らない場合は、削除するだけslow
です。画像はアップロード時にのみ表示されます:
$('#blah').hide();
$('#remove').hide();
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
if( $('#imgInp').val()!=""){
$('#remove').show();
$('#blah').show('slow');
}
else{ $('#remove').hide();$('#blah').hide('slow');}
readURL(this);
});
$('#remove').click(function(){
$('#imgInp').val('');
$(this).hide();
$('#blah').hide('slow');
$('#blah').attr('src','http://upload.wikimedia.org/wikipedia/commons/thumb/4/40/No_pub.svg/150px-No_pub.svg.png');
});
これは誰かが作成した例です(私ではありません:)が役立つと思います。以下のコードを参照してください。
function readPath(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readPath(this);
});
HTML コード:
<form id="form1">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>