Cropperjs裁剪图片并上传头像到七牛云

记录一下头像裁剪上传功能实现

效果图


Cropperjs裁剪图片并上传头像到七牛云_第1张图片
avatar.png

首先下载引入cropper js

npm install cropper js --save

js引入cropperjs

  import Cropper from "cropperjs";
  import "cropperjs/dist/cropper.css";

主要js方法代码

  methods: {
    dialogExit() {
      this.cropped = false
      this.loading = false
      this.$emit("exitUploadAvatar", {
        status: false
      })
        },
    submitUpload() {
            this.loading = true
      this.$refs.upload.submit();
    },
    uploadQiniu() {
      let _this = this;
      var blob = require('blueimp-canvas-to-blob');
      this.cropper.getCroppedCanvas().toBlob(function(blob) {
        _this.param = new FormData(); // 创建form对象
        _this.param.append("file", blob);
        _this.param.append("chunk", "0"); // 断点传输
        _this.param.append("chunks", "1");
        // console.log(_this.param.get("file"));
        let config = {
          headers: { "Content-Type": "multipart/form-data" },
          withCredentials:false
        };
        _this.$axios.get("api/avatarUpdate")
          .then(function(res) {
            _this.param.append("token", res.data.upToken);
            _this.param.append("key", res.data.filePath);
            _this.uploading(_this.param, config);
            // console.log(_this.param)
          })
          .catch(function(err){
            console.log(err)
          })
      },"image/jpeg",0.98);
    },
    uploading: function(param, config) {
      // 定义在data里的uploading函数
      let _this = this;
      console.log(param,config)
      this.$axios.post("https://up-z1.qiniup.com", param, config)
        .then(function(res){
          if(res.key){
            _this.loading = false
            _this.dialogExit()
            _this.$notify({
              title: '成功',
              message: '上传头像成功',
              type: 'success'
            })
          }
          // console.log("http://f.img.uwp.mobi/" + res.key)
                    // _this.updateBg(res.key)
        })
        .catch(function(err){
          console.log(err)
        })
    },
    change(file, fileList) {
      let _this = this;
      this.cropped = true;
      if (fileList.length > 1) {
        fileList.shift();
      }
      // console.log(file);
      // console.log(fileList);
      this.url = file.url;
      console.log(file);
      var image = document.getElementById("image");
      this.$nextTick(function() {
        if (_this.cropper) {
          _this.cropper.replace(_this.url);
        } else {
          _this.cropper = new Cropper(image, {
            aspectRatio: 1 / 1,
            viewMode: 1,
            preview: ".small",
            crop: function(e) {
              // console.log(e);
            }
          });
        }
      });
    }:

html代码如下

  

cropperjs 详细API https://github.com/fengyuanchen/cropperjs/blob/master/README.md

你可能感兴趣的:(Cropperjs裁剪图片并上传头像到七牛云)