繁体   English   中英

jQuery中的文件上传问题

[英]File upload problems in jQuery

这是一个上传按钮,用户可以从中选择文件

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

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

这是代码

 <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处理程序中使用URL.createObjectURL()和参数this.files[0]设置img src.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM