vue上传图片

这篇博客详细介绍了如何在 Vue.js 应用中实现图片上传功能,包括使用 Element UI 的上传组件、图片预览、删除、进度显示以及限制上传数量。同时,文章涵盖了图片格式检查和大小限制,以及在表单提交时如何处理图片数据。此外,还展示了如何通过 Axios 发送 HTTP 请求并将图片数据发送到服务器。
摘要由CSDN通过智能技术生成

vue上传图片

<el-form-item label="图标:" :inline="true">
        <el-upload
          action="#"
          list-type="picture-card"
          :class="{hide:hideBackgroundUploadEdit}"
          :on-preview="handlebackgroundPreview"
          :on-remove="handlebackgroundRemove"
          :on-change="handlebackgroundChange"
          :on-progress ="handlebackgroundProgress"
          :on-exceed="exceedFile"
          :http-request="uploadImage"
          :before-upload="beforeBackgroundUpload"
          :file-list="backgroundFile"
          :limit="1"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog title="图标" :append-to-body = true :visible.sync="newDialogVisible">
          <img width="100%" :src="dialogBackgroundUrl">
        </el-dialog>
      </el-form-item>

引入

import axios from 'axios'

data

ruleForm: {
          // 图标
          backgroundPicture:[],
          //如果haveBKPicture == 1 有图片就是编辑表单否则就是新增表单
          haveBKPicture:0,
        },
// 图标
        newDialogVisible:false,
        dialogBackgroundUrl:"",
        backgroundFile:[],
        backgroundSrc:"",
        hideBackgroundUploadEdit:false,

methods

// 图标
      handlebackgroundPreview(file) {
        this.dialogBackgroundUrl = file.url
        this.newDialogVisible = true
      },
      handlebackgroundChange(file, fileList) {
        this.hideBackgroundUploadEdit = fileList.length >= this.limitNum;
        if( fileList.length > 0 ){
          this.ruleForm.haveBKPicture = 1
        }else{
          this.ruleForm.haveBKPicture = 0
        }
      },
      handlebackgroundRemove(file, fileList) {
        this.ruleForm.haveBKPicture = 0
        this.hideBackgroundUploadEdit = fileList.length >= this.limitNum
      },
      handlebackgroundProgress(file){
      },
      uploadImage(item){
        this.ruleForm.backgroundPicture.push(item.file)
      },
      beforeBackgroundUpload(file){
        const isJPG = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG && !isPng) {
          this.$message.error('上传图片只能是 JPG或png 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return (isJPG || isPng) && isLt2M
      },
      exceedFile(files, fileList) {
        this.$notify.warning({
          title: '警告',
          message: `只能选择${this.limitNum}个文件`
        });
      },
      uploadImg() {
        this.$refs.uploadFile.submit()
      },
      backgroundUrl(backgroundIcon){
        this.backgroundFile = []
        const fileListObj = {}
        fileListObj.url = constant['weburl'] + "api" + backgroundIcon
        this.backgroundFile.push(fileListObj)
      },
      save() {
      	var formdata=new FormData();
      	this.ruleForm.backgroundPicture.forEach(function (file) {
          formdata.append('backgroundPicture',file);
          formdata.append("haveBKPicture",this.ruleForm.haveBKPicture)
        })
        this.$refs['ruleForm'].validate((valid) => {
              if (valid) {
                this.loading = true;
                const token = "token"
                const url1 = "ajax"+token
                axios({
                  url:url1,
                  method: 'post',
                  data: formdata,
                  headers:{
                    // 'Content-Type':'multipart/form-data',
                    'Content-Type':'multipart/form-data;boundary='+ new Date().getTime(),
                    token: "token"
                  }
                }).then(res=>{
                  try {
                    this.loading = false
                    if (res.data.data.ok == true) {
                      this.$message('保存成功!')
                      this.$emit('onload')
                      this.innerVisible = false
                    } else {
                      this.$message('必填字段不能为空')
                    }
                  } catch (e) {
                    this.$message(e)
                  }
                })
              }
            })
      }

style

.hide .el-upload--picture-card{
    display: none;
  }

for (let keys of formData.values()) {
console.log(keys);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值