外观
useUpload - 文件上传组合式函数
约 1099 字大约 4 分钟
2025-11-06
useUpload 是一个用于文件上传的组合式函数,支持多端一致的文件选择和上传功能。
快速开始
1. 导入 useUpload
<script setup lang="uts">
import { useUpload } from '@/uni_modules/uview-unix'
const { chooseFile, upload } = useUpload()
</script>2. 选择文件
// 选择图片
const files = await chooseFile({
accept: 'image',
sourceType: ['album', 'camera'],
compressed: true,
compressOptions: {
quality: 80,
width: 1080
}
} as UnChooseFileOptions)
// 选择视频
const videoFiles = await chooseFile({
accept: 'video',
sourceType: ['album'],
maxDuration: 30
} as UnChooseFileOptions)
// 选择文件
const documentFiles = await chooseFile({
accept: 'file',
sourceType: ['album']
} as UnChooseFileOptions)3. 上传文件
// 上传单个文件
const result = await upload({
url: 'https://api.example.com/upload',
file: files[0].file,
name: 'file',
header: {
'Authorization': 'Bearer token'
},
formData: {
'userId': '123'
}
} as UnUploadOptions)API 参考
chooseFile(options: UnChooseFileOptions)
选择文件的方法,返回选中的文件列表。
参数
| 参数 | 说明 | 类型 | 必填 | 默认值 |
|---|---|---|---|---|
| accept | 允许选择的文件类型,audio类型仅支持uniapp x | Enum | 否 | 'image' |
| sourceType | album 从相册选视频,camera 使用相机拍摄 | Array<string> | 否 | ['album', 'camera'] |
| compressed | 是否压缩所选的(图片/视频)源文件 | boolean | 否 | true |
| compressOptions | 图片压缩配置,详见下方配置项 | object | 否 | {} |
| extension | 允许选择的文件扩展名 | Array<string> | 否 | null |
| maxDuration | 视频最大时长(秒) | number | 否 | 10 |
| sizeType | 图片尺寸类型,可选值:'original'、'compressed' | Array<string> | 否 | ['original', 'compressed'] |
| camera | 相机方向,可选值:'back'、'front' | string | 否 | 'back' |
| mediaType | 媒体类型,可选值:'image'、'video' | Array<string> | 否 | ['image', 'video'] |
| maxCount | 最大选择数量 | number | 否 | 1 |
| multiple | 是否允许多选 | boolean | 否 | false |
compressOptions 配置项
详见 uni-app 官方文档 - compressImage
| 参数 | 类型 | 默认值 | 必填 | 说明 |
|---|---|---|---|---|
| quality | Number | 80 | 否 | 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效) |
| width | String | auto | 否 | 缩放图片的宽度,支持像素值(如"100px")、百分比(如"50%")、自动计算(如"auto",即根据width与源图宽的缩放比例计算,若未设置width则使用源图宽度) |
| height | String | auto | 否 | 缩放图片的高度,支持像素值(如"100px")、百分比(如"50%")、自动计算(如"auto",即根据height与源图高的缩放比例计算,若未设置height则使用源图高度) |
| compressedWidth | Number | - | 否 | 压缩后图片的宽度,单位为px,若不填写则默认以 compressedHeight 为准等比缩放 |
| compressedHeight | Number | - | 否 | 压缩后图片的高度,单位为px,若不填写则默认以 compressedWidth 为准等比缩放 |
| rotate | Number | 0 | 否 | 旋转度数,范围0~360 |
返回值
返回一个 Promise<UnChooseFile[]>,每个文件对象包含以下属性:
| 属性 | 说明 | 类型 |
|---|---|---|
| type | 文件类型,image/video等 | string |
| mime | MIME类型 | string |
| name | 文件名 | string |
| path | 文件路径 | string |
| size | 文件大小 | number |
| thumb | 缩略图路径(仅图片/视频类型有效) | string |
| file | 文件对象(H5平台为File对象) | any |
upload(options: UnUploadOptions)
上传文件的方法,返回上传结果。
参数
| 参数 | 说明 | 类型 | 必填 |
|---|---|---|---|
| url | 上传接口地址 | string | 是 |
| file | 要上传的文件对象 | any | 是 |
| name | 文件参数名 | string | 否 |
| header | 请求头 | object | 否 |
| formData | 额外的表单数据 | object | 否 |
返回值
返回一个 Promise<UnRequestSuccess>,包含上传结果。
示例
完整上传流程
<template>
<view>
<button @click="selectAndUpload">选择并上传图片</button>
<view v-if="uploadResult">
<text>上传成功:{{ uploadResult.data }}</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import { useUpload } from '@/uni_modules/uview-unix'
const { chooseFile, upload } = useUpload()
const uploadResult = ref<any>(null)
async function selectAndUpload() {
try {
// 选择图片
const files = await chooseFile({
accept: 'image',
sourceType: ['album'],
} as UnChooseFileOptions)
if (files.length > 0) {
// 上传文件
const result = await upload({
url: 'https://api.example.com/upload',
file: files[0].file,
name: 'image'
} as UnUploadOptions)
uploadResult.value = result
}
} catch (error) {
console.error('上传失败:', error)
}
}
</script>数据类型
/**
* 选择文件选项类型
* 用于配置文件选择的参数
*/
type UnChooseFileOptions = {
accept: "image" | "video" | "audio" | "all" | "file"
sourceType?: string[]
mediaType?: string[]
compressed?: boolean
compressOptions?: UTSJSONObject
maxDuration?: number
extension?: string[]
multiple?: boolean
sizeType?: string[]
camera?: 'front' | 'back'
maxCount?: number
}
/**
* 选择文件结果类型
* 用于表示选择的文件对象
*/
type UnChooseFile = {
type: string;
path: string;
mime?: string;
size?: number;
name?: string;
thumb?: string;
file?: any;
}
/**
* 上传选项类型
* 用于配置上传的参数
*/
type UnUploadOptions = {
url: string;
name?: string;
file?: any;
header?: UTSJSONObject;
formData?: UTSJSONObject;
}
/**
* 请求成功结果类型
* 用于表示请求成功的返回结果
*/
type UnRequestSuccess = {
data: any | string; // 响应数据
statusCode: number;
header: any;
cookies: string[];
tempFilePath: string;
};
/**
* 请求失败结果类型
* 用于表示请求失败的返回结果
*/
type UnRequestFail = {
errCode: number;
errSubject: string;
data?: any;
cause?: Error;
errMsg?: string;
};