thinkphp(php)+Ajax上传图片

原创
2016-08-08 09:23:32 945浏览

使用的外部插件:

  • jquery.form.js(表单提交) :http://malsup.com/jquery/form/#download

  • jquery.json.min.js(解析json数据):http://www.oschina.net/p/jquery-json

表单代码部分:

"img_file_upload" id="file_upload" name="file_upload"method="post" action="" enctype="multipart/form-data"> type="file" id="img" name="file"> type="hidden" name="member_id"value=""/> type="button"value="上传" >"submitImgForm()"/>
"show_photo_upload_img" src="" alt=""/>

js代码:

script>functionsubmitImgForm(){if ($("#img").val() == "") {
            alert("请选择一个图片文件,再点击上传。");
            return;
        }
        var file_form = $("[tag='img_file_upload']");
        var show_img = $("[tag='show_photo_upload_img']");
        var options = {
            type : 'post',
            url : "",
            dataType: 'text',
            contentType: "application/json; charset=utf-8",
            beforeSubmit:function(){
              alert('正在上传');
            },
            success:function(data) {var json_obj = JSON.parse(data);

                show_img.attr('src',json_obj.img_path);
                alert(json_obj.error);
            },
            error:function(XmlHttpRequest, textStatus, errorThrown){
                alert(textStatus);
                alert(errorThrown);
            }
        };

        file_form.ajaxSubmit(options);
    }
script>

后台php部分:

functionfileUpload(){$config = C('FILE_UPLOAD_CONFIG');
        //附带的信息$request_data = I('post.');
//        show_bug($request_data);$member_id = $request_data['member_id'];
        if(empty($the_file_usage)){
            $the_file_usage = $file_usage['DOWNLOAD'];
        }

//        show_bug_with_exit($file_name);$file_info['member_id'] = $member_id;
        $file_info['created_time'] = time();

            // 上传文件//实例化上传类,传入上面的配置数组$uploader = new Upload($config, 'Local');
//            $uploader->saveName = $file_uuid;$info = $uploader->upload($_FILES);
//        show_bug_with_exit($info);//这里判断是否上传成功if ($info) {
                //// 上传成功 获取上传文件信息foreach ($infoas &$file) {
                    //拼接出上传目录$file['rootpath'] = __ROOT__ . ltrim($config['rootPath'], ".");
                    //拼接出文件相对路径$file['filepath'] = $file['rootpath'] . $file['savepath'] . $file['savename'];
                }
                //这里可以输出一下结果,相对路径的键名是$info['upload']['filepath']$filepath = $file['filepath'];
//                show_bug_with_exit($filepath);$file_info['file_path'] = $filepath;


                $save_file_in_DB = $this->saveFileInfoIntoDB($file_info);
                //如果文件数据往数据库中存储失败,则删除文件if(!$save_file_in_DB){
                    unlink($filepath);
                    $return_data['error'] = '文件上传失败,请重试';
                    echo json_encode($return_data);
                }

                $return_data['error'] = '文件上传成功';
                $return_data['img_path'] = $filepath;
                $return_data['img_id'] = $save_file_in_DB;
                jsonReturn($return_data);
            } else {
                //输出错误信息$error_msg = $uploader->getError();
                $return_data['error'] = $error_msg;
                jsonReturn($return_data);
            }
    }


    functionsaveFileInfoIntoDB($file_info){$file = M('File');
        $rs_u_file = $file->add($file_info);
        $file_id = $file->getLastInsID();
        if(!$rs_u_file){
            returnfalse;
        }
        return$file_id;
    }

配置文件:

'FILE_UPLOAD_CONFIG'=>array(
        'mimes' => '', //允许上传的文件MiMe类型'maxSize' => 6 * 1024 * 1024, //上传的文件大小限制 (0-不做限制)'exts' => array('jpg', 'gif', 'png', 'jpeg'),// 设置附件上传类型'autoSub' => true, //自动子目录保存文件'subName' => array('date', 'Y-m-d'), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组'rootPath' => './Uploads/', //保存根路径'savePath' => '', //保存路径'saveName'   =>    array('uniqid',''),
    ),

function.php文件

/**
 * 返回json格式的数据到客户端
 * @access protected
 * @param mixed $data 要返回的数据
 * @return void
 */functionjsonReturn($data){$json_str = json_encode($data);
    // 返回JSON数据格式到客户端 包含状态信息
    header('Content-Type:application/json; charset=utf-8');
    //处理json中包含的‘null’,将其替换成空字符串$search = 'null';
    $replace = '""';
    $returndata = str_replace($search, $replace, $json_str);
//  testAddDataIntoTestTable(null,$returndata);exit($returndata);
}

以上就介绍了thinkphp(php)+Ajax上传图片,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。