uni-file-picker h5图片上传
时间: 2025-02-18 14:39:16 浏览: 41
### 使用 `uni-file-picker` 实现 H5 环境下的图片上传
为了在 H5 环境下使用 `uni-file-picker` 组件实现图片上传功能,可以按照如下方式配置组件并编写相应的逻辑处理函数。
#### HTML 部分
```html
<template>
<view class="container">
<!-- 图片选择器 -->
<uni-file-picker ref="filePicker" v-model="imageList" fileMediatype="image" mode="grid"
@select="handleSelect" @progress="handleProgress" @success="handleSuccess" />
<!-- 提交按钮 -->
<button type="primary" @click="submit">提交</button>
</view>
</template>
```
此部分创建了一个用于选择文件的 `uni-file-picker` 和一个触发上传操作的按钮[^1]。
#### JavaScript 部分
```javascript
<script>
export default {
data() {
return {
imageList: [], // 存储选中的图片信息
};
},
methods: {
handleSelect(e) {
console.log('选择了新的图片:', e.tempFiles);
// 如果需要立即上传可以选择在此处调用upload方法
},
handleProgress(event, item) {
// 更新进度条的状态
this.$refs.filePicker.setProgressByCustomUplaod(item.uuid, event.progress)[^2];
},
handleSuccess(res, item) {
console.log(`成功上传 ${item.name}`, res);
},
submit() {
const fileList = this.imageList;
if (!fileList.length) {
uni.showToast({
title: '请选择要上传的照片',
icon: 'none'
});
return;
}
fileList.forEach((item) => {
let uploadTask = uni.uploadFile({
url: 'https://example.com/api/upload', // 替换成实际服务器地址
filePath: item.path,
name: 'file',
formData: {},
success(response) {
console.log('单张图片上传完成');
}
});
// 取消上传任务示例
// uploadTask.abort();
});
}
}
};
</script>
```
上述代码展示了如何监听 `uni-file-picker` 的事件来响应用户的交互行为,并实现了当点击“提交”按钮时批量上传所选图片的功能。注意这里的 URL 应替换为实际的服务端接收接口路径。
对于希望控制更细致的情况,比如只允许上传一张头像而不展示删除按钮,则可以根据需求调整 `<uni-file-picker>` 标签内的属性设置,如 `limit`, `disable-preview`, `del-icon` 等参数[^3]。
阅读全文
相关推荐

















