在线文档教程

js简单的文件上传

<div class="orchat-img" onclick="openFileDialog()">点击上传</div>
<input type="file" id="filebutton" style="display:none" onchange="fileSelected()">
<img src="" alt="" id="img" > 
    <script type="text/javascript">
    function openFileDialog(){
        document.getElementById("filebutton").click();
    }
    function fileSelected() {
        var fbutton = $("#filebutton")[0]; //dom元素
        var reader = new FileReader();
        reader.onload = function (e) {
            var dataURL = e.target.result; 
            $("#img").attr("src",dataURL)
        };
        var file = fbutton.files[0];
        reader.readAsDataURL(file);
        ajaxup(file);
    }
    function ajaxup(file){  
        var formFile = new FormData();
        formFile.append("file",file); 
        var data = formFile;
        $.ajax({  
            url : "/admin-up-up.html",
            type : "POST",  
            data : data,  
            dataType:"text",  
            processData : false,
            contentType : false, 
            success:function(res){
                res = JSON.parse(res);
                if(res.code == 1){
                    layer.msg(res.msg);
                     $("#img").attr("src",res.data.url)
                }
            }
        }) 
    } 
    </script>