<?php

define('BASE_ROOT_PATH',str_replace('\\','/',dirname(__FILE__)));

function upfile_joutput_data($datas)
{
    $data = array();

    $data['code'] = 200;
    $data['message'] = 'SUCCESS';
    $data['datas'] = $datas;

    ob_clean();
    echo(json_encode($data));
}

function upfile_joutput_error()
{
    $data = array();
    $data['code'] = 15000;
    $data['message'] = "上传文件失败.";
    $data['datas'] = null;

    ob_clean();
    echo(json_encode($data));
}

function create_uuid($prefix = "") {
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str,0,8) . '-';
    $uuid .= substr($str,8,4) . '-';
    $uuid .= substr($str,12,4) . '-';
    $uuid .= substr($str,16,4) . '-';
    $uuid .= substr($str,20,12);
    return $prefix . $uuid;
}

if ($_POST)
{
    $base_path = BASE_ROOT_PATH . '/data/upload/upfile';
    $ret = array();

    if ($_FILES["file"]["error"] > 0) {
        upfile_joutput_error();
    }
    else
    {
        $fn = $_FILES["file"]["name"];
        $ext_name = '.' . strtolower(pathinfo($fn)['extension']);
        $dest_file = $base_path . '/' . date("YmdHis") . '-' . create_uuid() . $ext_name;
        $result = move_uploaded_file($_FILES["file"]["tmp_name"],$dest_file);
        if ($result) {
            $ret['file_path'] = $dest_file;
            upfile_joutput_data($ret);
        } else {
            upfile_joutput_error();
        }
    }
}