+
95
-

回答

首先从后端获取oss的地址及签名策略信息

<?php
function gmt_iso8601($time) {
date_default_timezone_set("Asia/Shanghai");
$dtStr = date("c", $time);
$mydatetime = new \DateTime($dtStr);
$expiration = $mydatetime->format(\DateTime::ISO8601);
$pos = strpos($expiration, '+');
$expiration = substr($expiration, 0, $pos);
return $expiration."Z";
}
$appid = '';
$appsecret = '';
$host = 'https://test.oss-cn-beijing.aliyuncs.com'; //你的oss地址
$callbackUrl = "http://oss-demo.aliyuncs.com:23450";

$callback_param = array('callbackUrl' => $callbackUrl,
'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
'callbackBodyType' => "application/x-www-form-urlencoded");
$callback_string = json_encode($callback_param);

$base64_callback_body = base64_encode($callback_string);
$now = time();
$expire = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问
$end = $now + $expire;
$expiration = gmt_iso8601($end);

$dir = 'tempimg/';//oss的上传目录

//最大文件大小.用户可以自己设置
$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, $appsecret, true));

$response = array();
$response['accessid'] = $appid;
$response['host'] = $host;
$response['policy'] = $base64_policy;
$response['signature'] = $signature;
$response['expire'] = $end;
$response['callback'] = $base64_callback_body;
//这个参数是设置用户上传指定的前缀
$response['dir'] = $dir;

echo json_encode($response);


可以,小程序端代码

    upload_file: function ( filePath) {
var that = this;
wx.request({
url: "后端签名策略地址url",
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res)

var filepathname = res.data.dir + filePath.replace("http://tmp/", '').replace("wxfile://", '');

wx.uploadFile({
url: res.data.host,
method: "POST",
filePath: filePath,
name: "file",
formData: {
key: filepathname,
policy: res.data.policy,
signature: res.data.signature,
OSSAccessKeyId: res.data.accessid,
success_action_status: '200',
callback: res.data.callback
},
header: {
'content-type': 'multipart/form-data'
},
success: function (res) {
wx.showToast({
title: "图片上传成功"
})

},
fail: function (res) {
wx.showToast({
title: "图片上传失败"
})

}
})
}

})
},

好了,完工


网友回复

我知道答案,我要回答