小兔网

两种js实现方式,一种用原生的ajax;另一种用JQuery,例子比较简单,直接上代码。

前端代码a.html

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
    <title>Title</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js"></script>
</head>
<body style="overflow: scroll; overflow-y: hidden; overflow-x: hidden">
    <div style="height: 20px"></div>
    <div class="container">
        <div class="row">

            <div class="col-md-6 col-md-offset-3">
                <form class="form-horizontal" enctype="multipart/form-data" role="form" id="testform">

                    <input type="hidden" value="1" id="id" name="id" />
                    <div class="control-group">
                        <label for="uname" class="col-md-3 control-label span3">姓 名:</label>
                        <div class="col-md-9">
                            <input type="text" class="form-control span3" value="" id="uname" name="uname"
                                placeholder="请输入姓名">
                        </div>
                    </div>

                    <div class="control-group">
                        <label for="pwd" class="col-md-3 control-label span3">密码:</label>
                        <div class="col-md-9">
                            <input type="password" class="form-control span3" value="" id="pwd" name="pwd"
                                placeholder="请输入密码">
                        </div>
                    </div>

                    <div class="control-group">
                        <label class="col-md-3 control-label span3"></label>
                        <div class="col-md-9">
                            <img src="/" width="100px" height="100px">
                        </div>
                    </div>

                    <div class="control-group">

                        <label for="requirement" class="col-md-3 control-label span3">图片上传</label>
                        <div class="col-md-9">
                            <div class="input-group">
                                <input id="photoCover" class="form-control" readonly type="text">
                                <label class="input-group-btn">
                                    <input id="file" type="file" name="file" style="left: -9999px; position: absolute;">
                                    <span class="btn btn-default">Browse</span>
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="control-group">
                        <label class="col-md-2 control-label span2"></label>
                        <div class="col-md-10">
                            <a class="btn btn-small btn-primary" onclick="saveUser()">方式一</a>
                            <a class="btn btn-small btn-danger" onclick="saveUser2()">方式二</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>

        //html5实现图片预览功能
        $(function () {
            $("#file").change(function (e) {
                var file = e.target.files[0] || e.dataTransfer.files[0];
                $('#photoCover').val(document.getElementById("file").files[0].name);
                if (file) {
                    var reader = new FileReader();
                    reader.onload = function () {
                        $("img").attr("src", this.result);
                    }

                    reader.readAsDataURL(file);
                }
            });
        })
        //方式一 Jquery实现
        function saveUser2() {
            var id = $("#id").val().trim();
            var uname = $("#uname").val().trim();
            var pwd = $("#pwd").val().trim();
            var file = document.getElementById("file").files[0];
            var formData = new FormData();
            formData.append('id', id);
            formData.append('uname', uname);
            formData.append('pwd', pwd);
            formData.append('file', file);

            $.ajax({
                url: "a.php",
                type: "post",
                data: formData,
                contentType: false,
                processData: false,
                mimeType: "multipart/form-data",
                success: function (data) {
                    console.log(data);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        }

        //方式二  原生ajax实现
        function saveUser() {
            var id = $("#id").val().trim();
            var uname = $("#uname").val().trim();
            var pwd = $("#pwd").val().trim();
            var file = document.getElementById("file").files[0];

            //原生ajax实现文件上传
            var formData = new FormData();
            formData.append("uname", uname); // 可以增加表单数据
            formData.append("id", id);
            formData.append("pwd", pwd);
            if (file) {
                formData.append("file", file);
            }

            //得到xhr对象
            var xhr = null;
            if (XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xhr.open("post", "a.php", true);//设置提交方式,url,异步提交
            xhr.onload = function () {
                var data = xhr.responseText;    //得到返回值
                alert(data);
            }
            xhr.send(formData);
        }
    </script>
</body>
</html>
 

 注意:

  1、用JQuery方式需要加两个参数 contentType: false 和processData: false,这两个参数是为了设置ajax对file文件对象进行序列化

  2、两种方式在组织参数时都需要使用var formData = new FormData()

后端处理代码a.php

<?php
//解决跨域问题
header("Access-Control-Allow-Origin:*");
//说明向前台返回的数据类型为JSON
//header("Content-type:text/json");
header('content-type:text/html charset:utf-8');
//$_FILES超全局变量存储是文件数据,是一个关联数组
$fileObj=$_FILES['file'];
var_dump($fileObj);
if($fileObj["error"]==0){
//判断文件是否合法
$types=["jpg","jpeg","png","gif"];
$type = explode("/", $fileObj["type"])[1];
if(in_array($type, $types)){
$time = time();//获取时间戳 返回一个整形
//获取文件详细路径
$filePath="https://xiaotut.com/xxx".$time.".".$type;
echo $filePath;
//移动文件
$res=move_uploaded_file($fileObj["tmp_name"],"xxx".$time.".".$type);
if($res){
$infor=array("err"=>0,"msg"=>"文件移动成功");
}else{
$infor=array("err"=>1,"msg"=>"文件移动失败");
}
}else{
$infor=array("err"=>1,"msg"=>"文件格式不合法");
}
echo json_encode($infor);
}
?>