2
代码如下(以组件形式调用):
<template>
<div class="img-upload" @click="clickContent">
<van-uploader
v-model="imgArr"
:before-read="beforeRead"
:max-count="maxCount"
deletable
:accept="accept"
multiple
class="pb-16"
@delete="onDelete()"
/>
</div>
</template>
<script>
import { Uploader } from 'vant';
import axios from 'axios'; // 引入axios
import { Toast } from 'vant'; // 引入Toast
import { bridge_upload } from '@/config/bridge';
export default {
name: 'LImgupLoader',
components: {
vanUploader: Uploader
},
props: {
// 图片绑定值
picArr: {
type: Array,
default: function() {
return [];
},
require: true
},
// 文件上传数量限制
maxCount: {
type: Number,
default: 1
},
// 接受的文件类型
accept: {
type: String,
default: 'image/*'
}
},
data() {
return {
imgArr: []
};
},
computed: {
},
watch: {
picArr: {
immediate: true,
handler(val, oldVal) {
this.imgArr = JSON.parse(JSON.stringify(val));
},
deep: true
}
},
mounted() {},
methods: {
clickContent() {
bridge_upload();
},
beforeRead(file) {
console.log('beforeRead--', file);
if (Array.isArray(file) && file.length) {
if (file.length > this.maxCount) {
Toast(`图片不能超过${this.maxCount}张`);
return;
}
file.forEach(item => {
// 文档上此用法在真机上出现bug item.type !== 'image/jpeg'
// if (item.type !== 'image/jpeg') {
// Toast('请上传图片格式');
// return false;
// }
this.upload(item);
});
} else {
// if (file.type !== 'image/jpeg') {
// Toast('请上传图片格式');
// return false;
// }
this.upload(file);
}
},
upload(file) {
// new 一个FormData格式的参数
const tokenURL = 'https://api.linhuiba.com/qiniu/app-token/linhuiba-certs';
const domain = 'https://cert.linhuiba.com/';
const params = new FormData();
params.append('file', file);
const config = {
headers: { // 添加请求头
'Content-Type': 'multipart/form-data'
}
};
axios.get(tokenURL).then(res => {
const token = res.data.result;
params.append('token', token);
// 把 uploadUrl 换成自己的 上传路径
axios.post('https://upload.qiniup.com', params, config).then(res => {
if (res && res.data && res.status === 200) {
this.imgArr.push({
url: `${domain}/${res.data.key}`,
file_name: file.name,
isImage: true // 图片需要加此参数才可以,详见vant
});
this.$emit('update:picArr', this.imgArr);
} else {
// 否则 Toast 提示
Toast.fail(res.data && (res.data.msg));
}
});
});
},
onDelete() {
this.$emit('update:picArr', this.imgArr);
}
}
};
</script>
<style lang='scss' scoped>
</style>