基础用法
mode="grid" ,可以使用九宫格样式选择图片
limit="1" ,则最多选择张图片
file-mediatype="image",限定只选择图片
file-extname='png,jpg',限定只选择 png和jpg后缀的图片文章来源:https://www.toymoban.com/news/detail-508221.html
auto-upload="false",可以停止自动上传,通过ref调用upload方法自行选择上传时机。与ref="files"搭配使用,this.$refs.files.upload()。文章来源地址https://www.toymoban.com/news/detail-508221.html
<uni-file-picker
v-model="imageValue"
file-mediatype="image"
mode="grid"
file-extname="png,jpg"
:limit="1"
@progress="progress"
@success="success"
@fail="fail"
@select="select"
/>
<script>
export default {
data() {
return {
imageValue:[]
}
},
methods:{
// 获取上传状态
select(e){
console.log('选择文件:',e)
},
// 获取上传进度
progress(e){
console.log('上传进度:',e)
},
// 上传成功
success(e){
console.log('上传成功')
},
// 上传失败
fail(e){
console.log('上传失败:',e)
}
}
}
</script>
案例一(只上传一张图片)
<template>
<view class="container example">
<uni-forms ref="baseForm" :modelValue="baseFormData" label-position="top">
<uni-forms-item label="图片上传">
<uni-file-picker
v-model="imageValue"
fileMediatype="image"
mode="grid"
@select="select"
limit="1"
></uni-file-picker>
</uni-forms-item>
</uni-forms>
</view>
</template>
export default {
data() {
return {
//图片
imageValue:[],
}
},
methods:{
//图片上传
select(e){
const tempFilePaths = e.tempFilePaths;
//获取图片临时路径
const imgUrl=tempFilePaths[0]
uni.uploadFile({
//图片上传地址
url: 'https://xxx.xxx.com/api/uploadpic/',
filePath: imgUrl,
//上传名字,注意与后台接收的参数名一致
name: 'imgUrl',
//设置请求头
header:{"Content-Type": "multipart/form-data"},
//请求成功,后台返回自己服务器上的图片地址
success: (uploadFileRes) => {
console.log('uploadFileRes',JSON.parse(uploadFileRes.data));
//处理数据
const path=JSON.parse(uploadFileRes.data)
//赋值,前端渲染
this.baseFormData.photo=path.imgUrl
}
});
},
}
}
图片展示
案例二(上传多张图片)
<template>
<view class="container example">
<uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules" label-position="top">
<uni-forms-item label="图片上传">
<uni-file-picker
v-model="imageValue"
fileMediatype="image"
mode="grid"
@select="select"
@delete="delIMG"
limit="9"></uni-file-picker>
</uni-forms-item>
</uni-forms>
</view>
</template>
<script>
export default {
data() {
return {
imgURL:'',
//图片
imageValue:[],
};
},
methods:{
//图片上传
select(e){
const tempFilePaths = e.tempFilePaths;
const imgUrl=tempFilePaths[0]
uni.uploadFile({
url: 'https://xxx.xxx.com/api/uploadpic2/',
filePath: imgUrl,
name: 'imgUrl',
header:{"Content-Type": "multipart/form-data"},
success: (uploadFileRes) => {
console.log('uploadFileRes',JSON.parse(uploadFileRes.data));
let path=JSON.parse(uploadFileRes.data)
//后端返回的地址,存入图片地址
this.imageValue.push({
url:this.imgURL+path.imgUrl,
name:''
})
console.log('imageValue',this.imageValue)
}
});
},
//图片删除
delIMG(e){
console.log('456',e)
const num = this.imageValue.findIndex(v => v.url === e.tempFilePath);
this.imageValue.splice(num, 1);
}
},
onLoad() {
//全局定义的图片访问地址前缀
this.imgURL=this.$imgURL
}
}
</script>
到了这里,关于uni-file-picker文件选择上传的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!