js图片上传和回显

一.css代码css

给<input>标签的父级设置一个‘+’背景图,把<input type=file>的宽高设置得跟父级同样,且彻底透明,html

这样点击的时候看似是点击的‘+’的节点,其实点击的是<input>节点。ajax

.file-box {
            position: relative;
            display: inline-block;
            width:100px;
            height:100px;
            background:url('images/uploadPc.png')no-repeat;
            background-size:100px 100px;
        }
#input_file{
            width:100%;
            height:100%;
            opacity: 0;
            filter:alpha(opacity=0);
        }json


二.html代码app

<div class="file-box">
       <input type="file" value="" name="file" id = "input_file"
          accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" οnchange="imgPreview(this,0)" >
</div>async

三.js代码svg

//这个方法是给$("#input_file")这个对象设置图片的值并回显图片post

function imgPreview(fileDom,i) {
        var reader = new FileReader();
        var file = fileDom.files[0];
        var imageType = /^image\//;
        if(!imageType.test(file.type)) {
            alert("请选择图片!");
            return;
        }this

        reader.readAsDataURL(file);
        reader.onload = function(e) {
            console.log(document.getElementsByClassName('file-box'));
            $('.file-box').css({"background":"url("+this.result+") no-repeat","backgroundSize":"200px 160px"});//回显
        };
    }
上传部分的代码:url

var formData = new FormData(); formData.append('photo', $('#input_file')[0].files[0]); $.ajax({             type: "post",             url:  "uploadaddress",             data: formdata,             dataType: 'json',             processData: false, // 告诉jQuery不要去处理发送的数据             contentType: false, // 告诉jQuery不要去设置Content-Type请求头             xhrFields:{withCredentials:true},             async: true,              success: function (data) {                 callback(data);             }         });

相关文章
相关标签/搜索