ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## uni.uploadFile(OBJECT) 将本地资源上传到开发者服务器,客户端发起一个 POST 请求,其中 content-type 为 multipart/form-data。 如页面通过 uni.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。 **OBJECT 参数说明** ``` 参数名 类型 必填 说明 平台支持 url String 是 开发者服务器 url files Aarry 否 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。 5+App filePath String 是 要上传文件资源的路径。 name String 是 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 header Object 否 HTTP 请求 Header, header 中不能设置 Referer formData Object 否 HTTP 请求中其他额外的 form data success Function 否 接口调用成功的回调函数 fail Function 否 接口调用失败的回调函数 complete Function 否 接口调用结束的回调函数(调用成功、失败都会执行) ``` **files参数说明 ** ``` files 参数是一个 file 对象的数组,file 对象的结构如下: name String 否 multipart 提交时,表单的项目名,默认为 file uri String 是 文件的本地地址 ``` **success 返回参数说明** ``` 参数 类型 说明 data String 开发者服务器返回的数据 statusCode Number 开发者服务器返回的 HTTP 状态码 ``` **返回值** 返回一个 uploadTask 对象,通过 uploadTask,可监听上传进度变化事件,以及取消上传任务。 ### uploadTask 对象的方法列表 ``` onProgressUpdate callback 监听上传进度变化 abort 中断上传任务 onProgressUpdate 返回参数说明 ``` ``` 参数 类型 说明 progress Number 上传进度百分比 totalBytesSent Number 已经上传的数据长度,单位 Bytes totalBytesExpectedToSend Number 预期需要上传的数据总长度,单位 Bytes ``` **实战:选择一个照片上传(带进度条)** ``` <template> <view> <view> <progress :percent="percent" stroke-width="10"></progress> </view> <view> <button type="primary" :loading="loading" :disabled="disabled" @click="upload">选择照片</button> </view> </view> </template> <script> var _self; export default { data:{ percent:0, loading:false, disabled:false }, methods : { upload : function(){ _self = this; uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有 sourceType: ['album'], //从相册选择 success: function (res) { const tempFilePaths = res.tempFilePaths; const uploadTask = uni.uploadFile({ url : 'https://demo.hcoder.net/index.php?c=uperTest', filePath: tempFilePaths[0], name: 'file', formData: { 'user': 'test' }, success: function (uploadFileRes) { console.log(uploadFileRes.data); } }); uploadTask.onProgressUpdate(function (res) { _self.percent = res.progress; console.log('上传进度' + res.progress); console.log('已经上传的数据长度' + res.totalBytesSent); console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend); }); }, error : function(e){ console.log(e); } }); } }, onLoad:function(){ } } </script> ``` **后端文件接收代码(php 版)** ``` <?php class uperTestController extends witController{ public function index(){ if(!empty($_FILES['file'])){ //获取扩展名 $exename = $this->getExeName($_FILES['file']['name']); if($exename != 'png' && $exename != 'jpg' && $exename != 'gif'){ exit('不允许的扩展名'); } $imageSavePath = uniqid().'.'.$exename; if(move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)){ echo $imageSavePath; } } } public function getExeName($fileName){ $pathinfo = pathinfo($fileName); return strtolower($pathinfo['extension']); } } ```