JS FormData 文件异步提交

Posted hnhycnlc888

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS FormData 文件异步提交相关的知识,希望对你有一定的参考价值。

html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta charset="utf-8">
  <meta name="generator" content="editplus" />
  <meta name="author" content="" />
  <meta name="keywords" content="" />
  <meta name="description" content="" />
 </head>

 <body>
<form id="form1" enctype="multipart/form-data">
姓&#12288;&#12288;名:<input class="input1" id="name"  name="name" type="text" maxlength="20" placeholder="" value="" /><font color="red">&nbsp;*</font><br/>
职&#12288;&#12288;位:<input class="input1" id="position"  name="position" type="text" maxlength="20" placeholder="" value="" />&nbsp;&nbsp;&nbsp;</font><br/>
手机号码:<input class="input1" id="phone"  name="phone" type="text" maxlength="11" placeholder="" value="" /><font color="red">&nbsp;*</font><br/>
公司名称:<input class="input1" id="company"  name="company" type="text" maxlength="20" placeholder="" value="" /><font color="red">&nbsp;*</font><br/>
<select id="inviter" class="input1" name="inviter">
    <option value="0">请选择邀请人</option>
    <option value="陈秉俊">陈秉俊</option>
    <option value="郭锦杭">郭锦杭</option>
    <option value="彭维鹏">彭维鹏</option>
    <option value="黎达丰">黎达丰</option>
    <option value="李活">李活</option>
    <option value="雷超">雷超</option>
</select>
<br>
<input type="file" name="photo" >
<br>
<input id="submit" class="submit" type="button" onclick="signup_submit()" value="立即报名" />
</form>
<script>
    if( $("#name").val().trim().length==0 ){
        alert("姓名不能为空");
        return false;
    }
    var patt = /^1d{10}$/;
    if( $("#phone").val().trim().length != 11 || !patt.test($("#phone").val().trim()) ){
        alert("手机号码格式不正确");
        return false;
    }
    if( $("#company").val().trim().length==0 ){
        alert("公司名称不能为空");
        return false;
    }
    if( $("#inviter").val().trim() == "0" ){
        alert("请选择邀请人");
        return false;
    }
    var formData = new FormData($(#form1)[0]);
    //var file = $(‘input[type="file"]‘).files[0];                              //formData对象下的方法有些浏览器不支持,移动端设备浏览器支持也存在问题
    //formData.append(‘photo‘, file);
    //formData.append(‘name‘, $("#name").val().trim());
    //formData.append(‘position‘, $("#position").val().trim());
    //formData.append(‘phone‘, $("#phone").val().trim());
    //formData.append(‘company‘, $("#company").val().trim());
    //formData.append(‘inviter‘, $("#inviter").val().trim());
    //console.log(formData.get(‘file‘));
    $.ajax({
        url: signup.php?act=reg,
        type: POST,
        cache: false,
        data: formData,
        dataType: json,
        async: false,          //同步
        processData: false,    //不需要对数据做任何预处理    true 会自动对form表单序列化处理 data: $(‘#form1‘)[0].serialize()
        contentType: false,    //不设置数据格式  如果contentType: true, 则提交数据的格式会自动变成application/x-www-form-urlencoded,后台接收不到$_FILES参数;文件上传,表单enctype="multipart/form-data"
        beforeSend: function () {
            $("#submit").val(正在提交...);
            $("#submit").prop(disabled,disabled);
        },
        complete: function () {
            $("#submit").val(立即报名);
            $("#submit").removeAttr("disabled");
        }
    }).success(function(res) {
        if(res.code != "0000"){
            console.log(res.msg);
        }else{
            $(#form1)[0].reset();
        }
        alert(res.msg);
    }).fail(function(res) {
        console.log(res)
    });
}
</script>
 </body>
</html>

 

php代码

<?php
header(‘Content-Type:application/json; charset=utf-8‘);
function getrandstr(){
    $str=‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890‘;
    $randStr = str_shuffle($str);//打乱字符串
    $rands= substr($randStr,0,6);//substr(string,start,length);返回字符串的一部分
    return $rands;
}

$db_config = require ‘config/db.php‘;
$con = mysql_connect($db_config[‘host‘], $db_config[‘user‘], $db_config[‘passwd‘]);
if (!$con)
{
    $return = array(
        ‘code‘ => 1001,
        ‘msg‘ => ‘数据库连接失败‘
    );
    echo json_encode($return);
    exit();
}

mysql_select_db($db_config[‘db‘], $con);
mysql_query("set names utf8");

if(isset($_GET[‘act‘]) && $_GET[‘act‘]==‘reg‘){
    $name = trim($_POST[‘name‘]);
    $position = trim($_POST[‘position‘]);
    $phone = trim($_POST[‘phone‘]);
    $company = trim($_POST[‘company‘]);
    $inviter = trim($_POST[‘inviter‘]);
    $photo = ‘‘;
    $ctime = date(‘Y-m-d H:i:s‘);
    $sql = " SELECT * FROM `user` WHERE `phone` = ‘{$phone}‘ ";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    if(empty($name) || mb_strlen($name,‘utf8‘)>20){
        $return = array(
            ‘code‘ => 1003,
            ‘msg‘ => ‘姓名格式不正确‘
        );
        echo json_encode($return);
        exit();
    }
    if(!preg_match(‘/^1d{10}$/‘, $phone)){
        $return = array(
            ‘code‘ => 1004,
            ‘msg‘ => ‘手机号码格式不正确‘
        );
        echo json_encode($return);
        exit();
    }
    if(empty($company) || mb_strlen($company,‘utf8‘)>20){
        $return = array(
            ‘code‘ => 1005,
            ‘msg‘ => ‘公司格式不正确‘
        );
        echo json_encode($return);
        exit();
    }
    if(empty($inviter) || mb_strlen($inviter,‘utf8‘)>20){
        $return = array(
            ‘code‘ => 1006,
            ‘msg‘ => ‘邀请人格式不正确‘
        );
        echo json_encode($return);
        exit();
    }
    if($row){
        $return = array(
            ‘code‘ => 1007,
            ‘msg‘ => $phone.‘ 手机号码硬件注册‘
        );
        echo json_encode($return);
        exit();
    }
    if ((($_FILES["photo"]["type"] == "image/gif")
                || ($_FILES["photo"]["type"] == "image/jpeg")
                || ($_FILES["photo"]["type"] == "image/pjpeg")
                || ($_FILES["photo"]["type"] == "image/png"))
            && ($_FILES["photo"]["size"] < 10 * 1024 * 1024))
    {
        if ($_FILES["photo"]["error"] <= 0)
        {
            $photo = getrandstr().‘_‘.strtotime(‘now‘).‘.‘.pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION);
            if (!file_exists("upload/" . $photo))
            {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $photo);
            }
        }
    }
    if($photo){
        $photo = ‘http://112.74.168.224/signup/upload/‘.$photo;
    }
    $sql = " INSERT INTO `user`(`name`,`position`, `phone`, `company`, `inviter`, `photo`, `checked`, `activity_id`, `ctime`)VALUES(‘{$name}‘, ‘{$position}‘, ‘{$phone}‘, ‘{$company}‘, ‘{$inviter}‘, ‘{$photo}‘, 0, 1, ‘{$ctime}‘) ";
    mysql_query($sql);
    mysql_close($con);
        $return = array(
            ‘code‘ => 0000,
            ‘msg‘ => ‘资料提交成功!我们会尽快通过短信与您联系,感谢您的支持!‘,
            ‘data‘ => array()
        );
        echo json_encode($return);
        exit();
}else{
    $url = "index.php";
    header("Location: $url");
    exit();
}

 

js对json的处理

JSON字符串:

var jsonStr = ‘{"name":"nikita", "password":"1111"}‘;

JSON对象:

var jsonObj = {"name":"nikita", "password":"1111"};




var last = JSON.stringify(jsonObj);   //将JSON对象转化为JSON字符


JSON.parse(jsonStr); //可以将json字符串转换成json对象 



eval(‘(‘ + jsonstr + ‘)‘); //可以将json字符串转换成json对象,注意需要在json字符外包裹一对小括号 
注:ie8(兼容模式),ie7和ie6也可以使用eval()将字符串转为JSON对象,但不推荐这些方式,这种方式不安全eval会执行json串中的表达式。

 

以上是关于JS FormData 文件异步提交的主要内容,如果未能解决你的问题,请参考以下文章

JQuery中使用FormData异步提交数据和提交文件

Node.js——异步上传文件

FormData对象

.Net之使用Jquery Ajax通过FormData对象异步提交图片文件到服务端保存并返回保存的图片路径

js 防止表单异步重复提交

面试题