vue+elementUI文件上传和图片上传

第一种 使用它的action方法

 <el-upload
          class="upload-demo"
          :headers="token"
          action="http://120.53.31.103:84/api/public/img"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="sizeForm.fileList"
          list-type="picture"
          :on-success="successImg"
        >
 <!-- 上传图片 headers提交token  action提交地址  on-success成功回调  三个比较重要    -->
  //这是标签中的token的数据源  token我们通过headers来进行传递
  data() {
    return {
     token: {
        Authorization: "Bearer" + localStorage.getItem("adminToken") || ""
      }
    };
  },


  //上传成功的回调函数
 successImg(res, file) {
      console.log(res, file);
      if (res.code === 200) {
      	//res.data.path 是服务器返回的当前图片的网络地址
        this.sizeForm.avatar = res.data.path;
        this.sizeForm.fileList.push(file);
        console.log(res.data.path);
      }
    }

第二种 不使用action

使用before-upload方法,这是文件上传前的钩子,它的参数就是当前操作的这个文件(就是上传的文件/图片)

执行的函数为

 		<el-upload
          class="upload-demo"
          action="abc"
          :limit="1"
          :show-file-list="false"
          :before-upload="onprog"
        >
          <el-button size="small" type="primary">上传文件</el-button>
        </el-upload>
 onprog(file) {
      //创建formdata实例
      var formData = new window.FormData();
      //将获取的文件通过append方法加入实例中
      formData.append("file", file);
      console.log(formData);
      //将formdata实例通过接口传递给服务器
      uploading_image(formData).then(res => {
        var type, message;
        console.log(res.data);
        if (res.data.code === 200) {
        	//文件内容不符合服务器需求  data的值是一个err数组  若符合data的值是一个数字
          if (res.data.data.err) {
            // type = "success";
            this.err = res.data.data.err;
            this.dialogVisible = true;
          } else {
            type = "success";
            message = `共${res.data.data}条,上传成功`;
            this.$message({
              type,
              message
            });
          }
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      });
    }

uploading_image是封装的请求 使用前要替换

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值