如何浏览img src javascript

时间:2013-09-25 15:00:06

标签: javascript jquery html

这是我需要做的。 所以我有这个代码

 <input type="file" id="uploadImage" name="image" />
    <input type="submit" id="ImageName" name="submit" value="Submit">

因此,当我单击“选择..”按钮浏览图像时,我希望将该图像的路径保存在变量中。

或者基本上我需要做的是使这条路径成为图像的src。

$('#Imageholder').append('<img src="" class="ImgCoords" >');

有什么想法吗?

对不起,如果解释不好:

2 个答案:

答案 0 :(得分:5)

以下是我所做的一个例子,根据您的需要进行调整:

DEMO HERE

我添加了一个按钮删除上传的文件,如果您不喜欢显示/隐藏效果,只需删除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');
});

HTML代码:

<form id="form1">
    <input type='file' id="imgInp" name='image'/>
    <img id="blah" src="#" alt="your image" />
</form>

答案 1 :(得分:1)

如果您使用HTML5,则可以。

通过 W3C

在此处查看File API.

API

的以下关键行
  var file = document.getElementById('file').files[0];

但如果你没有使用HTML5

出于安全原因,您无法执行该操作,无法访问文件系统信息。

明确有用:Preview an image before it is uploaded