let file = this.$refs.file.files[0] lrz(file, { width: 450, fieldName: 'file' }).then((rst) => {
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://xxx.com/upload')
xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 304) {
// 无论后端抛出何种错误,都会走这里
try {
// 如果后端跑异常,则能解析成功, 否则解析不成功
let resp = JSON.parse(xhr.responseText)
console.log('response: ', resp)
} catch (e) {
this.imageUrl = xhr.responseText
}
}
}
// 添加参数
rst.formData.append('folder', 'wxAvatar') // 保存的文件夹
rst.formData.append('base64', rst.base64)
// 触发上传
xhr.send(rst.formData)
return rst
})
}
单个图片上传组件完整代码,如下(注: icon图标使用的是svg-icon组件):
<template>
<div class="imgUploader">
<section v-if="imageUrl"
class="file-item ">
<img :src="imageUrl"
alt="">
<span class="file-remove"
@click="remove()">+</span>
</section>
<section v-else
class="file-item">
<div class="add">
<svg-icon v-if="!text"
class="icon"
icon-class="plus" />
<span v-if="text"
class="text">{{text}}</span>
<input type="file"
accept="image/*"
@change="selectImgs"
ref="file">
</div>
</section>
</div>
</template><script>
import lrz from 'lrz'
export default {
props: {
text: String,
// 压缩尺寸,默认宽度为450px
size: {
type: Number,
default: 450
}
},
data () {
return {
img: {
name: '',
src: ''
},
uploadUrl: 'http://ff-ff.xxx.cn/UploaderV2/Base64FileUpload',
imageUrl: ''
}
},
watch: {
imageUrl (val, oldVal) {
this.$emit('input', val)
},
value (val) {
this.imageUrl = val
}
},
mounted () {
this.imageUrl = this.value
},
methods: {
// 选择图片
selectImgs () {
let file = this.$refs.file.files[0] lrz(file, { width: this.size, fieldName: 'file' }).then((rst) => {
var xhr = new XMLHttpRequest()
xhr.open('POST', this.uploadUrl)
xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 304) {
// 无论后端抛出何种错误,都会走这里
try {
// 如果后端跑异常,则能解析成功, 否则解析不成功
let resp = JSON.parse(xhr.responseText)
console.log('response: ', resp)
} catch (e) {
this.imageUrl = xhr.responseText










