先安装,我使用composer安装
在项目的根目录运行composer require aliyuncs/oss-sdk-php
微信小程序页面
<l-image-picker count="9" bind:linchange="onChangeTap" />
js页面
//文件上传之后的方法
onChangeTap(event) {
//获取最新上传的所有图片临时路径
let tempFilePaths = event.detail.current;
//定义一个空数组,进行存放上传图片url
var urlArr = [];
for (let index = 0; index < tempFilePaths.length; index++) {
wx.uploadFile({
url: 'http://www.front.com/api/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[index],
name: 'file',
header:{
'thonk':wx.getStorageSync('thonk')
},
success: res => {
const data = JSON.parse(res.data);
//do something
urlArr.push(data.url)
this.setData({
urls: urlArr
})
}
})
}
},
php后台代码
public function upload()
{
//要上传文件的临时路径
$filePath = $_FILES['file']['tmp_name'];
//阿里云上传对象存储
$fileName = (new OssServer())->uploadFile($filePath);
return json(['error_code'=>0,'url'=>$fileName,'msg'=>'操作成功']);
}
comment里面创建一个oss
public function uploadFile($filePath)
{
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
$accessKeyId = config('oss.accessKeyId');
$accessKeySecret = config('oss.accessKeySecret');
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = config('oss.endpoint');
// 存储空间名称
$bucket = config('oss.bucket');
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
$fileName = date('Y-m-d', time()) . '/' . md5(time() . rand(1111, 9999999)) . '.png';
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$result = $ossClient->putObject($bucket, $fileName, file_get_contents($filePath));
} catch (OssException $e) {
print $e->getMessage();
}
return $result['info']['url'];
}
config里oss.php
return [
'accessKeyId'=>'LTAI5tLSMnGQgzk3uAEjQwa8',
'accessKeySecret'=>'Zcw7yUAnRbWZxEqASkhgE35EbbbBxI',
'endpoint'=>'http://oss-cn-shanghai.aliyuncs.com',
'bucket'=>'',
];