Basic usage
mode="grid" , you can use the Jiugongge style to select pictures
limit="1" , select at most pictures
file-mediatype="image", limit to select only pictures
file-extname='png,jpg', only select images with png and jpg suffixes
auto-upload="false", you can stop the automatic upload, and call the upload method by ref to choose the upload timing by yourself. Used with ref="files", this.$refs.files.upload().
<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>
Case 1 (Only upload a picture)
<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
}
});
},
}
}
image display
Case 2 (upload multiple pictures)
<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>