Use jquery ajax asynchronous upload files

Formdata objects can be achieved using the asynchronous file upload

html code (note that the form enctype attribute must be multipart / form-data)

<form id="form1" enctype="multipart/form-data">
    <input type="text" name="name">
    <input type="text" name="pwd">
    <input type="text" name="cid">
    <input id="file" type="file" name="file">

     <input id="btn" type="button" value="保存">
</form>

js code

$("#btn").on("click", function(){
        //注意,formData是表单中的对象,$("#form1")[0]是DOM表单对象而不是input对象
        var formData = new FormData($("#form1")[0]);
        //往formData插入普通的表单数据以便与文件一起提交到服务器
        var data=$('form').serializeArray();
        $.each(data,function(index,item){
            formData.append(item.name,item.value);
        });
        $.ajax({
            url: '__URL__/test1',//数据提交的目标文件
            type: 'POST',
            data: formData, // 上传formdata封装的数据
            dataType: 'JSON',
            cache: false,                      // 不缓存
            processData: false,                // jQuery不要去处理发送的数据
            contentType: false,                // jQuery不要去设置Content-Type请求头
            success:function (data) {           //成功回调
                console.log(data);
            }
        });
    });

note:

1. Create a FormData incoming object parameter must be a form object! DOM object can not be and must be the object when iQuery

2. after the completion of the above steps can be verified in the background $ _FILES [ 'file'] whether there is (php language), if there is documentation to upload properly, there is no description is intended not to submit files unsuccessful.

3.FormData can insert normal form data and documents to be submitted, but can only be found in the $ _POST common policy data, information files $ _FILES [ 'name attributes submit'] in

php code (ThinkPHP3.2 controller code)

public function test1(){
        $data=I('post.');
//        $this->ajaxReturn($_FILES['file']);//用于测试前端数据是否上传成功
        if(IS_POST){
            if($_FILES['file']['error']==0){
                $config=array(
                    'rootPath'=>'./Application/public/uploads/'//配置文件上传的路径
                );
                $upload=new \Think\Upload($config);//创建upload对象
                $info=$upload->uploadOne($_FILES['file']);
                $this->ajaxReturn($info);
            }
        }

    }

Guess you like

Origin blog.csdn.net/wwz123124/article/details/80720564