Blogger Information
Blog 29
fans 0
comment 0
visits 46608
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用ajax上传并预览图片后传到服务器上
盼盼love的博客
Original
2055 people have browsed it

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>利用js的FormData对象快速收集表单信息及无刷新上传头像</title>

    <style>

        #preview, .img, img {

            width: 200px;

            height: 200px;

        }

 

        #preview {

            border: 1px solid #000;

        }

    </style>

</head>

<body>

<form enctype="multipart/form-data" id="tf" onsubmit="return false">

    用户名:<input type="text" name="user"><br/>

    密码:<input type="password" name="pass"><br/>

    头像:<input type="file" name="file"  onchange="preview(this)"><br/>

    <div id="preview"></div>

 

    <input type="submit" value="提交" onclick="test()">

</form>

<script type="text/javascript" src="jquery-1.8.3.min.js"></script>

<script type="text/javascript">

 

    function test(){

        var form = new FormData(document.getElementById("tf"));

        //             var req = new XMLHttpRequest();

        //             req.open("post", "${pageContext.request.contextPath}/public/testupload", false);

        //             req.send(form);

        $.ajax({

            url:"upload.php",

            type:"post",

            data:form,

            processData:false,

            contentType:false,

            success:function(data){

                window.clearInterval(timer);

                console.log("over..");

            },

            error:function(e){

                alert("错误!!");

                window.clearInterval(timer);

            }

        });

    }

 

    function preview(file) {

        var prevDiv = document.getElementById('preview');

        if (file.files && file.files[0]) {

            var reader = new FileReader();

            reader.onload = function(evt) {

                prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';

            }

            reader.readAsDataURL(file.files[0]);

        } else {

            prevDiv.innerHTML = '<div style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';

        }

    }

</script>

</body>

</html>


upload.php


<?php

var_dump($_FILES);die;//这里直接写自己后台逻辑咯

?>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post