jQuery 中的文件上传问题

File upload problems in jQuery

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

基本上我想做的是每当用户从中选择图像时, 它应该显示在 "trees" 图片所在的位置。

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

这是代码

<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”中显示图像

尝试将 change 事件附加到 input type="file" 元素,在 change 处理程序中使用带有参数 this.files[0]URL.createObjectURL() 来设置 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>

使用此代码,当您尝试使用文件控制器上传图像时,该图像在 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>