jQuery中的文件上传问题

时间:2015-10-24 01:46:39

标签: php jquery html css upload

here is an upload button, from which user can choose the file

基本上我想做的是每当用户从中选择图像时, 它应该显示在“树”图像所在的地方。

我被困了,真的需要一些帮助。

这是代码

<div class="user-editable-div">	
		<div class="image-div" id="image_div"><img src="images/image.jpg" id="bg_image" /></div>
		<span class="upload-btn">UPLOAD IMAGE</span>
		<input type="file" id="uploader" />
		<div class="content-div">
			<h1 contenteditable="true">USER EDITABLE</h1>
			<p contenteditable="true">All elements on this page are user editable. You can edit them by simply clicking or by clicking on the edit button next to the element.</p>
	</div>
</div>

当用户从“#uploader”中选择一个文件时,它应该以“#bg_image”显示图像

2 个答案:

答案 0 :(得分:0)

尝试将change事件附加到input type="file"元素,在URL.createObjectURL()处理程序中使用this.files[0]参数change来设置src img.attr(attribute, value)

$(":file").change(function(e) {
  $("#bg_image").attr("src", URL.createObjectURL(this.files[0]))
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="user-editable-div">	
		<div class="image-div" id="image_div"><img id="bg_image"src="" /></div>
		<span class="upload-btn">UPLOAD IMAGE</span>
		<input type="file" id="uploader" accept="image/*" />
		<div class="content-div">
			<h1 contenteditable="true">USER EDITABLE</h1>
			<p contenteditable="true">All elements on this page are user editable. You can edit them by simply clicking or by clicking on the edit button next to the element.</p>
	</div>
</div>

答案 1 :(得分:0)

当您尝试使用使用文件控制器上传图像时使用此代码bg_image元素中的图像预览

   <div class="user-editable-div">  
        <div class="image-div" id="image_div"><img src="images/image.jpg" id="bg_image" /></div>
        <span class="upload-btn">UPLOAD IMAGE</span>
        <input type="file" id="uploader" onchange="readURL(this,this.id);"/>
        <div class="content-div">
            <h1 contenteditable="true">USER EDITABLE</h1>
            <p contenteditable="true">
              All elements on this page are user editable. You can edit them by simply clicking or by clicking on the edit button next to the element.
            </p>
        </div>
    </div>

   <script>
function readURL(input,ids)
{
    if (input.files && input.files[0])
        {
            var reader = new FileReader();
            reader.onload = function (e)
            {
                $('#bg_image').attr('src', e.target.result).width(650).height(375);
            };
            reader.readAsDataURL(input.files[0]);
        }
}       
</script>