日期: 2018 年 8 月 7 日

  • 使用iview的upload组件上传阿里oss的参数设置

    下面是组件设置:

    <Upload action="http://public.files.dpexpo.cn"
    ref="upload"
    :show-upload-list="false"
    accept=".pdf"
    :format="['pdf']"
    :on-success="uploadSuccess"
    :data="uploadParams"
    :max-size="102400"
    :before-upload="handleBeforeUpload">
    <Buttontype="ghost"
    icon="ios-cloud-upload-outline">Upload pdf</Button>
    </Upload>
    以下是相关的js方法:

    handleBeforeUpload(file) {
    letthat=this;
    return new Promise(function(resolve, reject) {
    that.getUploadParams().then(function() {
    that.$Notice.warning({
    title:'文件准备上传',
    desc:'文件 '+file.name+' 准备上传。',
    duration:3
    });
    resolve();
    });
    });
    },
    getUploadParams() {
    varthat=this;
    return new Promise(function(resolve, reject) {
    that.$http// 在此方法中调用后台数据
    .get('/ossParams', {
    params: {
    dir:
    'slide/conference/'+
    that.$route.query.conference_id+
    '/'
    }
    })
    .then(function(response) {
    console.log(response);
    that.uploadParams=JSON.parse(response.data.data);
    console.log(that.uploadParams);
    resolve();
    })
    .catch(function(error) {
    console.log(error);
    });
    });
    },
    uploadSuccess(evnet, file) {
    console.log(file);
    this.$Notice.success({
    title:'文件上传成功',
    desc:'文件 '+file.name+' 上传成功。',
    duration:3
    });
    this.formValidate.slide_url=
    'http://public.files.dpexpo.cn/slide/conference/'+
    this.$route.query.conference_id+
    '/'+
    file.name;
    },

    以下是发放参数的api方法(laravel):

    public function ossParams(Request $request)
    {
    $id = 'LTA(your id)V1E';
    $key = '4M5nIHs(your key)IelsW';
    $host = 'http://public.files.dpexpo.cn';
    $now = time();
    $expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问
    $end = $now + $expire;
    $expiration = $this->gmt_iso8601($end);
    $dir = $request->dir ? $request->dir : 'user-dir/';
    //最大文件大小.用户可以自己设置
    $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
    $conditions[] = $condition;
    //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
    $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
    $conditions[] = $start;
    $arr = array('expiration' => $expiration, 'conditions' => $conditions);
    //echo json_encode($arr);
    //return;
    $policy = json_encode($arr);
    $base64_policy = base64_encode($policy);
    $string_to_sign = $base64_policy;
    $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
    $response = array();
    //$response['host'] = $host;
    $response['key'] = $dir.'${filename}';
    $response['policy'] = $base64_policy;
    $response['OSSAccessKeyId'] = $id;
    $response['Signature'] = $signature;
    $response['expire'] = $end;
    //这个参数是设置用户上传指定的前缀
    //$response['dir'] = $dir;
    $token = json_encode($response);
    return$this->response->array(['data' => $token]);
    }