|

官方教程:https://help.aliyun.com/document_detail/92883.html
个人整理:
第一步:跨域设置里设置规则

第二步:小程序后台配置uploadfile的域名

第三步:制作一个生成签名后端接口
主要生成:policy signature 也可以吧OSSAccessKeyId后端返回
代码如下:
- $key= ''; // 请填写您的AccessKeySecret。
- $now = time();
- $expire = 10000; //设置该policy超时时间是10s. 即这个policy过了这个有效时间,将不能访问。
- $end = $now + $expire;
- $expiration = $this->gmt_iso8601($end);
- //最大文件大小.用户可以自己设置
- $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
- $conditions[] = $condition;
- $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
- $policy = json_encode($arr);
- $base64_policy = base64_encode($policy);
- $response['policy'] = $base64_policy;
- $string_to_sign = $base64_policy;
- $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
- $response['signature'] = $signature;
- $this->ajaxReturn($response);
复制代码
第四步,微信小程序代码
参数解释:
1:filePath 指本地图片文件地址
2:host 就是第二步填写的上传域名
3:key 保存到阿里云OSS上的文件名
4:policy signature 都是通过第三步后端返回的
- wx.uploadFile({
- url: host, // 开发者服务器的URL。
- filePath: filePath,
- name: 'file', // 必须填file。
- formData: {
- key,
- policy,
- OSSAccessKeyId: '',
- signature,
- // 'x-oss-security-token': securityToken // 使用STS签名时必传。
- },
- success: (res) => {
- if (res.statusCode === 204) {
- console.log('上传成功');
- }
- },
- fail: err => {
- console.log(err);
- }
- });
复制代码
|
|