Ajax图片上传

1、定义上传的图片展示和按钮


    
        
        
        
        {if $data.userInfo.avatar}
        
{else}
{/if}

支持扩展名:.png .gif .jpg...

2、点击时调用的上传功能的函数

/**
 * 上传图片
 * id  attribute data-id
 * url attribute data-url
*/
function uploadFile(files,imageId) {
    //获取元素的data-id
    var id = files.attr('data-id');
    if(imageId){
        var imageBox = $("#"+imageId).find('img');
    }
    var url = files.attr('data-url');
    var files = files.get(0).files[0];
    var obj = files;
    data = new FormData();
    data.append("file", obj);
    $.ajax({
        data: data,
        type: "POST",
        url: url,
        cache: false,
        contentType: false,
        processData: false,
        success: function(res) {
            $("#"+id).val(res.id);
            if(imageId){
                imageBox.attr('src',res.path);
            }else{
                toastr.success("文件上传成功");
                $("#imageLight").text("上传成功");
            }
        }
    },'JSON');
}

3、先定义好文件上传处理函数

/**
 * 上传文件
 * @param $directory 存放目录,所有上传文件按类型分目录保存。
 * @return array data中保存files表ID
 * array (size=3)
 * 'code' => string '1' (length=1)
 * 'msg' => string '上传成功' (length=18)
 * 'data' =>string '1,2'//file表id
 */
function upload($directory = "", $extarr = array('jpg','JPG', 'gif','GIF', 'png','PNG','jpeg','GPEG', "xlsx", "docx", "rar", "zip", "doc", "xls", "txt", "ppt", "pptx", "pdf"), $dftsize =15,$ret='',$fmt="")
{
    $files = request()->file();
    $i = 0;
    $result = array();
    $rlt=array();
    //\think\Log::notice(json_encode($files));
    if(count($files)>0) {
        foreach ($files as $file) {
            $data = array();
            $fileInfo = $file->getInfo();

            $fileName = $fileInfo["name"];

            $filesize = $file->getSize();
            //判断文件大小
            if ($filesize > $dftsize * 1024 * 1024) {
                return returnResult("file_info", "file_size_err");
            }
            if (false !== strpos($fileName, ".")) {
                //$name = substr($fileName,0,strrpos($fileName,"."));
                $exts = substr($fileName, strrpos($fileName, ".") + 1, strlen($fileName) - strrpos($fileName, ".") - 1);
            } else {
                $exts = "";
            }
            $filesize=$filesize/(1024 * 1024);
            //判断文件类型
            if (!empty($extarr) && !in_array($exts, $extarr)) {
                return returnResult("file_info", "file_exts_err");
            }
            $tmppath = "/files/" . $directory;
            //$tmppath = "/huizhi/developer/filerepo/videoevlt/" . $directory;
            $savename = session("userId") . "-" . time() . "-" . rand(1, 100000) . "-" . $i . "." . $exts;
            $info = $file->move(ROOT_PATH . 'public' . $tmppath, "/" . $savename);
            $i++;
            $fullpath = $info->getPathName();
            if (false !== $info) {
                $data['fileName'] = $fileName;
                $data['savePath'] = substr($fullpath, strrpos($fullpath, $tmppath));
                $data['saveName'] = $savename;
                $data['exts'] = $exts;
                $data['size'] = $filesize;
                $data['uploadUserId'] = session('userId');
                $data['uploadTime'] = date('Y-m-d H:i:s', time());
                //保存文件到数据库
                $id = db('sysFile')->insertGetId($data);
                if (!empty($id)) {
                    if (empty($ret)) {
                        $result[] = $id;
                    } else {
                        $result[] = $data['savePath'];
                    }

                    if(!empty($fmt)){
                        $rlt["id"]=$id;
                        $rlt["savepath"]=$data['savePath'];
                    }
                } else {
                    return returnResult("file_info", "file_upload_err");
                }
            } else {
                // 上传失败获取错误信息
                //\think\Log::notice("22");
                return returnResult("file_info", "file_upload_err", $file->getError());
            }
        }
    }else {
        // 上传失败获取错误信息
        //\think\Log::notice(json_encode($files));
        return returnResult("file_info", "file_upload_err", "上传失败");
    }
    if(!empty($fmt)){
        return returnResult("file_info", "file_upload_suc", $rlt);
    }else{
        return returnResult("file_info", "file_upload_suc", join(",", $result));
    }

}

4、再使用定义好的查询函数

/**
 * 获取单个字段在数据库中存取值
 * @param $table 表名
 * @param $con 查询条件
 * @param $field 需要返回字段
 * @return null|string 返回空或者字段值
 */
function getField($table, $con = array(), $field = "name",$default='',$join=[])
{
    try {
        $field=trim($field);
        $data = findById($table, $con, $field,$join);
        if ($data["code"] === '1') {
            $field=substr(" ".$field,strrpos(" ".$field," ")+1);
            return $data['data'][$field];
        }
    } catch (\Exception $e) {
        c_Log($e);
        return $default;
    }
    return $default;
}

5、前台请求后台的地址函数

/**
     * 上传图片
     * @return $res  path data
     */
    public function ajaxUploads(){
        $res = upload();
        $path = getField('SysFile',array('id'=>$res['data']),'savepath');
        $data['path'] = '/public'.$path;
        $data['id'] = $res['data'];
        return json($data);
    }

你可能感兴趣的:(Ajax图片上传)