文章目录
- 一、今日学习目标
- 二、实战步骤
- 1. 了解uni.chooseImage(OBJECT)
- 2. 了解uni.uploadFile(OBJECT)
- 3. 在项目中上传图片
- 图片上传进度监听 uploadTask()
一、今日学习目标
二、实战步骤
1. 了解uni.chooseImage(OBJECT)

- 特别说明下
crop
参数,是图像裁剪
的参数

| |
| uni.chooseImage({ |
| count: 6, |
| sizeType: ['original', 'compressed'], |
| sourceType: ['album'], |
| success: function (res) { |
| console.log(JSON.stringify(res.tempFilePaths)); |
| } |
| }); |
复制
使用注意事项:
- count 值在 H5 平台的表现,基于浏览器本身的规范。目前测试的结果来看,只能限制单选/多选,并不能限制数量。并且,在实际的手机浏览器很少有能够支持多选的。
- sourceType 值在 H5 平台根据浏览器的不同而表现不同,一般不可限制仅使用相册,部分浏览器也无法限制是否使用相机。
2. 了解uni.uploadFile(OBJECT)
- 介绍:将本地资源上传到开发者服务器,客户端发起一个 POST 请求,其中 content-type 为
multipart/form-data

| |
| uni.chooseImage({ |
| success: (chooseImageRes) => { |
| const tempFilePaths = chooseImageRes.tempFilePaths; |
| uni.uploadFile({ |
| url: 'https://www.example.com/upload', |
| filePath: tempFilePaths[0], |
| name: 'file', |
| formData: { |
| 'user': 'test' |
| }, |
| success: (uploadFileRes) => { |
| console.log(uploadFileRes.data); |
| } |
| }); |
| } |
| }); |
复制
3. 在项目中上传图片
| |
| uni.chooseImage({ |
| count: 1, |
| sizeType: ['original', 'compressed'], |
| sourceType: ['album', 'camera'], |
| success: (res) => { |
| const tempFilePaths = res.tempFilePaths; |
| console.log(tempFilePaths[0]) |
| _this.logo_list = tempFilePaths[0] |
| uni.uploadFile({ |
| url: 'https://xx.com/center/group/icon', |
| filePath: tempFilePaths[0], |
| name: 'groupicon', |
| header:{ |
| "Authorization": userinfo.token |
| }, |
| success: (res) => { |
| let group = JSON.parse(res.data) |
| uni.showToast({ |
| title:"上传成功", |
| icon:"success" |
| }) |
| } |
| }); |
| } |
| }); |
复制
图片上传进度监听 uploadTask()
在uniapp中上传图片,需要uni.chooseImage()和uni.uploadFile()这两个api结合使用,才能完成图片的上传,还有一个uploadTask(),
可以用来监听上传进度变化事件
,和取消上传任务
。我们根据项目需求去决定要不要添加这个监听行为。

| |
| uploadTask.onProgressUpdate((res) => { |
| console.log('上传进度' + res.progress); |
| console.log('已经上传的数据长度' + res.totalBytesSent); |
| console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend); |
| |
| |
| if (res.progress > 50) { |
| uploadTask.abort(); |
| } |
| }); |
| |
复制