1
0
mirror of https://github.com/ialley-workshop-open/uni-halo.git synced 2026-09-12 16:40:40 +08:00

refactor: 架构升级

This commit is contained in:
小莫唐尼
2026-08-31 07:58:23 +08:00
commit ba5b77568b
693 changed files with 118430 additions and 0 deletions
@@ -0,0 +1,234 @@
# uni.downloadFile - 下载文件示例
## 官方文档
参考官方文档:https://doc.dcloud.net.cn/uni-app-x/api/request/network-file.html#downloadfile
## 概述
`uni.downloadFile` 用于下载文件资源到本地。
## 基础用法
```javascript
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
console.log('下载成功', res.tempFilePath)
}
})
```
## 完整示例
### 示例 1: 下载图片
```javascript
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功', res.tempFilePath)
// 可以预览或保存图片
uni.previewImage({
urls: [res.tempFilePath]
})
}
},
fail: (err) => {
console.error('下载失败', err)
}
})
```
### 示例 2: 下载并保存到相册
```javascript
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
if (res.statusCode === 200) {
// 保存到相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({
title: '保存成功',
icon: 'success'
})
},
fail: (err) => {
console.error('保存失败', err)
}
})
}
}
})
```
### 示例 3: 显示下载进度
```javascript
uni.downloadFile({
url: 'https://example.com/large-file.pdf',
success: (res) => {
console.log('下载完成', res.tempFilePath)
},
fail: (err) => {
console.error('下载失败', err)
}
})
```
### 示例 4: 在页面中使用
```vue
<template>
<view class="container">
<button @click="downloadFile">下载文件</button>
<view v-if="downloading" class="download-status">
<text>下载中...</text>
</view>
<view v-if="filePath" class="file-info">
<text>文件路径{{ filePath }}</text>
<button @click="openFile">打开文件</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
downloading: false,
filePath: ''
}
},
methods: {
downloadFile() {
this.downloading = true
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
this.filePath = res.tempFilePath
this.downloading = false
uni.showToast({
title: '下载成功',
icon: 'success'
})
}
},
fail: (err) => {
this.downloading = false
uni.showToast({
title: '下载失败',
icon: 'none'
})
}
})
},
openFile() {
// 打开文件
uni.openDocument({
filePath: this.filePath,
success: () => {
console.log('打开成功')
}
})
}
}
}
</script>
```
### 示例 5: 封装下载函数
```javascript
// utils/download.js
const download = {
downloadFile(url, options = {}) {
return new Promise((resolve, reject) => {
uni.downloadFile({
url: url,
header: options.header || {},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.tempFilePath)
} else {
reject(new Error(`下载失败,状态码:${res.statusCode}`))
}
},
fail: (err) => {
reject(err)
}
})
})
},
async downloadAndSave(url) {
try {
const filePath = await this.downloadFile(url)
// 根据文件类型保存
if (filePath.endsWith('.jpg') || filePath.endsWith('.png')) {
await uni.saveImageToPhotosAlbum({ filePath })
} else {
await uni.saveFile({ tempFilePath: filePath })
}
return filePath
} catch (err) {
throw err
}
}
}
// 使用
download.downloadFile('https://example.com/file.pdf')
.then(filePath => {
console.log('下载成功', filePath)
})
.catch(err => {
console.error('下载失败', err)
})
```
## 参数说明
| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| url | String | 是 | 下载资源的 url |
| header | Object | 否 | HTTP 请求 Header |
## 返回值
| 参数名 | 类型 | 说明 |
|--------|------|------|
| tempFilePath | String | 临时文件路径,下载后的文件会存储到一个临时文件 |
| statusCode | Number | HTTP 状态码 |
## 平台兼容性
| 平台 | 支持情况 |
|------|---------|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
## 注意事项
1. 下载的文件是临时文件,需要保存才能永久使用
2. 可以通过 `statusCode` 判断下载是否成功
3. 下载的文件路径是临时路径,应用关闭后可能失效
4. 建议下载后立即保存或使用
## 参考资源
- **官方文档**: https://doc.dcloud.net.cn/uni-app-x/api/request/network-file.html#downloadfile
- **保存文件**: https://doc.dcloud.net.cn/uni-app-x/api/file/file.html#savefile
- **打开文档**: https://doc.dcloud.net.cn/uni-app-x/api/file/file.html#opendocument
@@ -0,0 +1,287 @@
# uni.request - 网络请求示例
## 官方文档
参考官方文档:https://doc.dcloud.net.cn/uni-app-x/api/request/request.html
## 概述
`uni.request` 用于发起网络请求,支持 GET、POST、PUT、DELETE 等方法。
## 基础用法
### GET 请求
```javascript
uni.request({
url: 'https://api.example.com/data',
method: 'GET',
success: (res) => {
console.log('请求成功', res.data)
},
fail: (err) => {
console.error('请求失败', err)
}
})
```
### POST 请求
```javascript
uni.request({
url: 'https://api.example.com/user',
method: 'POST',
data: {
name: 'John',
age: 30
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log('请求成功', res.data)
}
})
```
## 完整示例
### 示例 1: 带参数的 GET 请求
```javascript
uni.request({
url: 'https://api.example.com/users',
method: 'GET',
data: {
page: 1,
limit: 10
},
success: (res) => {
if (res.statusCode === 200) {
console.log('用户列表', res.data)
}
},
fail: (err) => {
uni.showToast({
title: '请求失败',
icon: 'none'
})
}
})
```
### 示例 2: POST 请求上传数据
```javascript
uni.request({
url: 'https://api.example.com/users',
method: 'POST',
data: {
name: 'John Doe',
email: 'john@example.com',
age: 30
},
header: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
success: (res) => {
if (res.statusCode === 200 || res.statusCode === 201) {
uni.showToast({
title: '创建成功',
icon: 'success'
})
}
}
})
```
### 示例 3: 使用 Promise
```javascript
// Promise 方式(部分平台支持)
uni.request({
url: 'https://api.example.com/data'
}).then(res => {
console.log('请求成功', res.data)
}).catch(err => {
console.error('请求失败', err)
})
```
### 示例 4: 封装请求函数
```javascript
// utils/request.js
const request = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
...options.header
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(new Error(`请求失败: ${res.statusCode}`))
}
},
fail: (err) => {
reject(err)
}
})
})
}
// 使用
request({
url: 'https://api.example.com/data',
method: 'GET'
}).then(data => {
console.log('数据', data)
}).catch(err => {
console.error('错误', err)
})
```
### 示例 5: 请求拦截和响应拦截
```javascript
// utils/http.js
const baseURL = 'https://api.example.com'
// 请求拦截
const requestInterceptor = (config) => {
// 添加 token
const token = uni.getStorageSync('token')
if (token) {
config.header = {
...config.header,
'Authorization': `Bearer ${token}`
}
}
return config
}
// 响应拦截
const responseInterceptor = (res) => {
if (res.statusCode === 401) {
// token 过期,跳转登录
uni.navigateTo({
url: '/pages/login/login'
})
return Promise.reject(new Error('未授权'))
}
return res.data
}
const http = {
request(options) {
const config = requestInterceptor({
url: baseURL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: options.header || {}
})
return new Promise((resolve, reject) => {
uni.request({
...config,
success: (res) => {
try {
const data = responseInterceptor(res)
resolve(data)
} catch (err) {
reject(err)
}
},
fail: (err) => {
reject(err)
}
})
})
}
}
export default http
```
### 示例 6: 超时处理
```javascript
uni.request({
url: 'https://api.example.com/data',
method: 'GET',
timeout: 5000, // 5秒超时
success: (res) => {
console.log('请求成功', res.data)
},
fail: (err) => {
if (err.errMsg && err.errMsg.includes('timeout')) {
uni.showToast({
title: '请求超时',
icon: 'none'
})
} else {
uni.showToast({
title: '请求失败',
icon: 'none'
})
}
}
})
```
### 示例 7: 处理不同数据类型
```javascript
// JSON 数据
uni.request({
url: 'https://api.example.com/data',
dataType: 'json',
success: (res) => {
console.log('JSON 数据', res.data)
}
})
// 文本数据
uni.request({
url: 'https://api.example.com/text',
dataType: 'text',
success: (res) => {
console.log('文本数据', res.data)
}
})
// ArrayBuffer 数据
uni.request({
url: 'https://api.example.com/binary',
responseType: 'arraybuffer',
success: (res) => {
console.log('二进制数据', res.data)
}
})
```
## 平台差异
- **H5**: 支持 `withCredentials` 参数,用于跨域请求携带凭证
- **App**: 支持 `sslVerify` 参数,用于验证 SSL 证书
- **App**: 支持 `firstIpv4` 参数,DNS 解析时优先使用 IPv4
## 注意事项
1. 默认超时时间为 60000ms(60秒)
2. 默认 `dataType``json`,会自动解析 JSON 数据
3. 请求 header 中不能设置 `Referer`
4. 部分平台支持 Promise 方式调用
5. 建议封装统一的请求函数,便于统一处理错误和拦截
## 参考资源
- **官方文档**: https://doc.dcloud.net.cn/uni-app-x/api/request/request.html
- **网络请求最佳实践**: https://doc.dcloud.net.cn/uni-app-x/api/request/request.html
@@ -0,0 +1,262 @@
# uni.uploadFile - 上传文件示例
## 官方文档
参考官方文档:https://doc.dcloud.net.cn/uni-app-x/api/request/network-file.html#uploadfile
## 概述
`uni.uploadFile` 用于将本地资源上传到服务器。
## 基础用法
```javascript
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: '/tmp/image.jpg',
name: 'file',
success: (res) => {
console.log('上传成功', res.data)
}
})
```
## 完整示例
### 示例 1: 上传图片
```javascript
// 先选择图片
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
// 上传图片
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: tempFilePath,
name: 'file',
formData: {
'user': 'test'
},
success: (uploadRes) => {
const data = JSON.parse(uploadRes.data)
console.log('上传成功', data.url)
uni.showToast({
title: '上传成功',
icon: 'success'
})
},
fail: (err) => {
console.error('上传失败', err)
uni.showToast({
title: '上传失败',
icon: 'none'
})
}
})
}
})
```
### 示例 2: 上传多张图片
```javascript
uni.chooseImage({
count: 9,
success: (res) => {
const tempFilePaths = res.tempFilePaths
let uploadCount = 0
tempFilePaths.forEach((filePath, index) => {
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: filePath,
name: 'file',
success: () => {
uploadCount++
if (uploadCount === tempFilePaths.length) {
uni.showToast({
title: '全部上传成功',
icon: 'success'
})
}
},
fail: (err) => {
console.error(`${index + 1}张图片上传失败`, err)
}
})
})
}
})
```
### 示例 3: 显示上传进度
```javascript
uni.chooseImage({
count: 1,
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: tempFilePath,
name: 'file',
success: (res) => {
console.log('上传成功', res)
},
fail: (err) => {
console.error('上传失败', err)
}
})
}
})
```
### 示例 4: 在页面中使用
```vue
<template>
<view class="container">
<button @click="uploadImage">上传图片</button>
<view v-if="uploading" class="upload-status">
<text>上传中...</text>
</view>
<image v-if="imageUrl" :src="imageUrl" mode="aspectFit" class="uploaded-image"></image>
</view>
</template>
<script>
export default {
data() {
return {
uploading: false,
imageUrl: ''
}
},
methods: {
uploadImage() {
uni.chooseImage({
count: 1,
success: (res) => {
this.uploading = true
const tempFilePath = res.tempFilePaths[0]
uni.uploadFile({
url: 'https://api.example.com/upload',
filePath: tempFilePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
success: (uploadRes) => {
const data = JSON.parse(uploadRes.data)
this.imageUrl = data.url
this.uploading = false
uni.showToast({
title: '上传成功',
icon: 'success'
})
},
fail: (err) => {
this.uploading = false
uni.showToast({
title: '上传失败',
icon: 'none'
})
}
})
}
})
}
}
}
</script>
```
### 示例 5: 封装上传函数
```javascript
// utils/upload.js
const upload = {
uploadImage(filePath, options = {}) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: options.url || 'https://api.example.com/upload',
filePath: filePath,
name: options.name || 'file',
formData: options.formData || {},
header: options.header || {},
success: (res) => {
try {
const data = JSON.parse(res.data)
resolve(data)
} catch (e) {
resolve(res.data)
}
},
fail: (err) => {
reject(err)
}
})
})
}
}
// 使用
const filePath = '/tmp/image.jpg'
upload.uploadImage(filePath, {
url: 'https://api.example.com/upload',
formData: { userId: '123' }
}).then(data => {
console.log('上传成功', data)
}).catch(err => {
console.error('上传失败', err)
})
```
## 参数说明
| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| url | String | 是 | 开发者服务器地址 |
| filePath | String | 是 | 要上传文件资源的路径 |
| name | String | 是 | 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容 |
| header | Object | 否 | HTTP 请求 Header |
| formData | Object | 否 | HTTP 请求中其他额外的 form data |
## 返回值
| 参数名 | 类型 | 说明 |
|--------|------|------|
| data | String | 服务器返回的数据 |
| statusCode | Number | HTTP 状态码 |
## 平台兼容性
| 平台 | 支持情况 |
|------|---------|
| H5 | ✅ |
| 微信小程序 | ✅ |
| 支付宝小程序 | ✅ |
| 百度小程序 | ✅ |
| 字节跳动小程序 | ✅ |
| QQ 小程序 | ✅ |
| 快手小程序 | ✅ |
| App | ✅ |
| 快应用 | ✅ |
## 注意事项
1. 上传文件前需要先选择文件(使用 `uni.chooseImage` 等)
2. `filePath` 必须是本地路径
3. 可以通过 `formData` 传递额外的表单数据
4. 建议在请求头中添加认证信息
## 参考资源
- **官方文档**: https://doc.dcloud.net.cn/uni-app-x/api/request/network-file.html#uploadfile
- **选择图片**: https://doc.dcloud.net.cn/uni-app-x/api/media/image.html#chooseimage
- **下载文件**: https://doc.dcloud.net.cn/uni-app-x/api/request/network-file.html#downloadfile