外观
useUpload - 文件上传组合式函数
约 775 字大约 3 分钟
2025-11-06
介绍
useUpload 封装了 uni-app 的文件选择与上传能力,chooseFile 按 accept 自动切换 chooseImage / chooseVideo / chooseMedia / chooseFile 并统一返回文件列表,upload 返回接口响应的解析结果。
基本用法
import { useUpload } from '@/uni_modules/uview-unix'
const { chooseFile, upload } = useUpload<{ code: number, data: any }>()
const files = await chooseFile({
accept: 'image',
sourceType: ['album', 'camera'],
compressed: true,
compressOptions: { quality: 80, width: 1080 }
})
const res = await upload({
url: 'https://api.example.com/upload',
name: 'file',
filePath: files[0].path,
header: { Authorization: 'Bearer token' },
formData: { userId: '123' }
})API
useUpload<T>(): UnUseUpload<T>
返回包含 chooseFile 与 upload 两个方法的对象,泛型 T 用于指定 upload 的返回类型。
chooseFile(options: UnChooseFileOptions): Promise<UnChooseFile[]>
根据 accept 选择对应的平台 API:
| accept | 使用的 API |
|---|---|
| image | uni.chooseImage |
| video | uni.chooseVideo |
| media、mix | uni.chooseMedia |
| all、audio、file | uni.chooseFile |
参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| accept | 选择类型:image、video、media(mix 同义)、all、audio、file | string | 'image' |
| sourceType | 来源:album 相册、camera 相机;chooseImage 原样传递,chooseMedia / chooseVideo 未传时使用相册与相机 | string[] | ['album', 'camera'] |
| mediaType | 媒体类型,仅 chooseMedia 使用 | string[] | ['image', 'video'] |
| compressed | 选择后是否压缩文件(图片走压缩,视频在有原生压缩能力时压缩) | boolean | false |
| compressOptions | 压缩配置,透传给 uni.compressImage / uni.compressVideo,常用字段 quality、width、height、rotate,视频可用 bitrate、fps、resolution | Record<string, any> | {} |
| maxDuration | 视频最大时长,单位秒 | number | 平台默认 |
| extension | 允许的扩展名,空数组时不传递 | string[] | [] |
| multiple | 是否多选,为 false 时选择数量固定为 1 | boolean | false |
| sizeType | 图片尺寸类型,如 'original'、'compressed' | string[] | 平台默认 |
| camera | 相机方向,如 'back'、'front' | string | 平台默认 |
| maxCount | 最大选择数量,仅在 multiple 为 true 时生效 | number | 1 |
| albumMode | 相册模式,仅图片与视频选择使用 | string | 平台默认 |
| pageOrientation | 页面方向,仅图片、视频、媒体选择使用 | string | 平台默认 |
| crop | 裁剪配置,仅图片选择使用 | Record<string, any> | 平台默认 |
返回值
返回 Promise<UnChooseFile[]>,每个文件对象结构如下:
| 属性 | 说明 | 类型 |
|---|---|---|
| type | 文件类型,如 image、video、file | string |
| path | 文件路径 | string |
| mime | MIME 类型 | string |
| size | 文件大小,单位字节 | number |
| name | 文件名 | string |
| thumb | 缩略图路径,图片为自身路径,视频为缩略图 | string |
| duration | 视频时长,单位秒 | number |
| file | 文件对象,H5 端为 File,其他端为路径 | any |
选择文件(accept 为 file、all、audio)时不执行压缩。
upload<T>(options: UnUploadOptions): Promise<T>
调用 uni.uploadFile 上传文件,成功时把响应体 data 通过 JSON.parse 解析后 resolve,失败时 reject。
参数
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| url | 上传接口地址 | string | - |
| name | 文件参数名 | string | 'file' |
| file | 待上传的 File 对象,仅 H5 / Web 有效;传入对象时忽略 filePath | any | - |
| filePath | 待上传文件的路径,非 H5 平台必填 | string | - |
| header | 请求头 | Record<string, any> | - |
| formData | 额外的表单数据 | Record<string, any> | - |
| getTask | 获取上传任务对象,用于监听进度或取消上传 | (task: any) => void | - |
返回值
| 返回值 | 说明 | 类型 |
|---|---|---|
Promise<T> | 上传成功时返回响应体解析后的 JSON 对象;请求失败时 reject | Promise<T> |
