vue上传图片,并回显图片
<input v-show="false" type="file" accept="image/*" @change="tirggerFile($event)" ref="input" /> <div style="" @click="openImg" class="changeimgurl"> <span v-if="changeimg==''">点击上传文章附图</span> <img style="height:100%;width:100%;" v-if="changeimg!=''" :src="changeimg" /> </div> <van-button ref="button" plain hairline type="info" size="normal" class="changeimg" @click.prevent="submitupdataimg">+提交图片</van-button>
export default {
data () {
return {
changeimg: '' } }, methods: {
// 预览上传头像图片 tirggerFile: function (event) {
const file = event.target.files[0] console.log(file) console.log(file.size) if (file.size > (5 * 1024 * 1024)) {
Toast.fail('图片大小不能超过 5M') return 'error' } this.file = file let url = '' var reader = new FileReader() reader.readAsDataURL(file) const that = this console.log(reader) reader.onload = function (e) {
url = this.result.substring(this.result.indexOf(',') + 1) // 图像预显base64路径 that.changeimg = 'data:image/png;base64,' + url } }, openImg () {
this.$refs.input.click() }, // 将数据提交给服务器 submitupdataimg () {
console.log('提交图片') // this.$refs.button.setAttribute('disabled', 'disabled') console.log(this.file) var testfile = this.file // alert提示框,确定是否需要上传。 async function beforeClose (action, done) {
if (action === 'confirm') {
setTimeout(done, 500) console.log(testfile) console.log(testfile.name) if (testfile.name === undefined) {
Toast.fail('请重新选择需要上传的图片') return 'error' } // 提交上传图片的路径 const forms = new FormData() forms.append('file', testfile) // 获取上传图片信息 const result = await uploadimage(forms) console.log(result) if (result.status === 200) {
console.log('上传图片成功') // 增加禁用button按钮的禁止点击事件,防止多次点击,多次提交数据 this.$refs.button.setAttribute('disabled', 'disabled') } else {
alert('上传图片失败') } } else {
// alert('取消上传图片') setTimeout(done, 500) } } Dialog.confirm({
title: '上传图片', message: '确定要上传图片吗?', beforeClose }) }, } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230679.html原文链接:https://javaforall.net
