FormData 上传图片 vue

本文介绍如何在Vue.js应用中利用FormData对象上传图片,包括处理文件选择、创建FormData实例、发送AJAX请求到服务器的过程,以及前端验证和错误处理的实现。
uploadPhoto(event){
      var $file = event.currentTarget;
      var file = $file.files;
      let totallen = this.fileList.length+file.length
      if(totallen>4){
        this.$toast('最多上传4张图片!')
          return false
      }
      for (var i = 0; i < file.length; i++) {
        var formData = new FormData()
        // 文件名称,文件对象
        if (file[i].type !== 'image/jpeg' && file[i].type !== 'image/png') {
          this.$toast('只允许上传jpg/png格式的图片!')
          return false
        }
        formData.append("uploadFile", file[i])
        formData.append("tenantId", 'visit')
        formData.append("type",file[i].type.replace('image/',''))
      this.$toast.loading({
        message: "加载中...",
        duration: 0,
        forbidClick: true,
      });
      axios({
          method: 'post',
          url:this.url,
          data:formData,
          headers: {'Content-Type': 'multipart/form-data; boundary=something','token':window.localStorage.getItem('userToken')},
          timeout: 10000
        }).then((res)=>{
          this.$toast.clear();
            if(res.status == 200){
              res.data.forEach(item=>{
                this.fileList.push({
                  localPath: item.path,
                  uploadUrl: item.path,
                  checkinId: this.recId,
                  path: item.path,
                  createTime: new Date(),
                  createUser: this.userName,
                  createUserName: this.realName
                })
              })
            } else {
              this.$toast("上传失败");
            }
          })
          .catch(function (error) {
            this.$toast("上传失败");
          });
      }
    },
 <div
                class="upload-img upload-button"
                v-if="fileList.length<4"
              >
              <input type = "file" accept="image/*" multiple   class='inputbox' @change='uploadPhoto'/>
              </div>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值