欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue-cropper组件实现图片切割上传

程序员文章站 2022-03-10 17:17:20
本文实例为大家分享了vue-cropper组件实现图片切割上传的具体代码,供大家参考,具体内容如下这几日,等来了些空闲,用vue和spring boot实践一次头像上传,因此记下了,望将来的开发有所帮...

本文实例为大家分享了vue-cropper组件实现图片切割上传的具体代码,供大家参考,具体内容如下

这几日,等来了些空闲,用vue和spring boot实践一次头像上传,因此记下了,望将来的开发有所帮助。

vue-cropper在vue中的引入

1、组件内引入

import { vuecropper }  from 'vue-cropper' 
components: {
  vuecropper,
},

2、全局引入

在main.js中配置如下代码

import vuecropper from 'vue-cropper' 

vue.use(vuecropper)

3、使用示例

vue文件

<template>
  <el-dialog
    title="编辑头像"
    :visible.sync="dialogformvisible"
    :close-on-click-modal="false"
    append-to-body
  >
    <label class="btn" for="uploads">选择图片</label>
    <input
      type="file"
      id="uploads"
      :value="imgfile"
      style="position:absolute; clip:rect(0 0 0 0);"
      accept="image/png, image/jpeg, image/gif, image/jpg"
      @change="uploadimg($event, 1)"
    >
    <div style="margin-left:20px;">
      <div class="show-preview" :style="{'overflow': 'hidden', 'margin': '5px'}">
        <div :style="previews.div" class="preview" style="width: 40px;height: 40px;">
          <img :src="previews.url" :style="previews.img">
        </div>
      </div>
    </div>
    <div class="cut">
      <vuecropper
        ref="cropper"
        :img="option.img"
        :outputsize="option.size"
        :outputtype="option.outputtype"
        :info="true"
        :full="option.full"
        :canmove="option.canmove"
        :canmovebox="option.canmovebox"
        :original="option.original"
        :autocrop="option.autocrop"
        :autocropwidth="option.autocropwidth"
        :autocropheight="option.autocropheight"
        :fixedbox="option.fixedbox"
        @realtime="realtime"
        @imgload="imgload"
      ></vuecropper>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogformvisible = false" size="small">取 消</el-button>
      <el-button type="primary" @click="finish('blob')" size="small">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { vuecropper } from "vue-cropper";
export default {
  components: {
    vuecropper
  },
  data() {
    return {
      previews: {},
      model: false,
      modelsrc: "",
      filename: "",
      imgfile: "",
      dialogformvisible: false,
      option: {
        img: "",
        outputsize: 1, //剪切后的图片质量(0.1-1)
        full: false, //输出原图比例截图 props名full
        outputtype: "png",
        canmove: true,
        original: false,
        canmovebox: true,
        autocrop: true,
        autocropwidth: 40,
        autocropheight: 40,
        fixedbox: true
      }
    };
  },
  methods: {
    //上传图片(点击上传按钮)
    finish(type) {
      let selft = this;
      let formdata = new formdata();
      // 输出
      if (type === "blob") {
        selft.$refs.cropper.getcropblob(data => {
          let img = window.url.createobjecturl(data);
          selft.model = true;
          selft.modelsrc = img;
          formdata.append("file", data, selft.filename);
          selft.$api.writer.userupload(formdata, r => {
            if (r.code) {
              selft.$alert.error(r.msg);
            } else {
              selft.$message({
                message: r.data.msg,
                type: "success"
              });
              selft.$store.state.userinfo = r.data.data;
              selft.dialogformvisible = false;
            }
          });
        });
      } else {
        this.$refs.cropper.getcropdata(data => {});
      }
    },
    //选择本地图片
    uploadimg(e, num) {
      console.log("uploadimg");
      var selft = this;
      //上传图片
      var file = e.target.files[0];
      selft.filename = file.name;
      if (!/\.(gif|jpg|jpeg|png|bmp|gif|jpg|png)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new filereader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把array buffer转化为blob 如果是base64不需要
          data = window.url.createobjecturl(new blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        if (num === 1) {
          selft.option.img = data;
        } else if (num === 2) {
          selft.example2.img = data;
        }
      };
      // 转化为base64
      // reader.readasdataurl(file)
      // 转化为blob
      reader.readasarraybuffer(file);
    },
    show() {
      this.dialogformvisible = true;
    },
    // 实时预览函数
    realtime(data) {
      console.log("realtime");
      this.previews = data;
    },
    imgload(msg) {
      console.log("imgload");
      console.log(msg);
    }
  }
};
</script>

<style lang="less">
@import "./userlogo.less";
</style>

less文件

.cut {
    width: 300px;
    height: 300px;
    margin: 0px auto;
}

.hh {
    .el-dialog__header {
        padding: 0px;
        line-height: 2;
        background-color: #f3f3f3;
        height: 31px;
        border-bottom: 1px solid #e5e5e5;
        background: #f3f3f3;
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
    }
    .el-dialog__title {
        float: left;
        height: 31px;
        color: #4c4c4c;
        font-size: 12px;
        line-height: 31px;
        overflow: hidden;
        margin: 0;
        padding-left: 10px;
        font-weight: bold;
        text-shadow: 0 1px 1px #fff;
    }
    .el-dialog__headerbtn {
        position: absolute;
        top: 8px;
        right: 10px;
        padding: 0;
        background: 0 0;
        border: none;
        outline: 0;
        cursor: pointer;
        font-size: 16px;
    }
}

.btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    //margin: 20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all 0.2s ease;
    text-decoration: none;
    user-select: none;
}

.show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview {
        overflow: hidden;
        border-radius: 50%;
        border: 1px solid #cccccc;
        background: #cccccc;
    }
}

发送请求的时候配置axios的content-type

// http request 拦截器
axios.interceptors.request.use(
  config => {debugger
    let token = sessionstorage.getitem('token')
    if (token) {
      config.headers.authorization = token;
    }
    if (config && config.url && config.url.indexof('upload') > 0) {
      config.headers['content-type'] = 'multipart/form-data'
    }
    return config
  },
  err => {
    return promise.reject(err)
  }
)

boot的controller

@requestmapping("/upload")
 public resultdata upload(@requestparam("file") multipartfile file) {
  return userservice.upload(file);
 }

boot的service

@override
 public resultdata upload(multipartfile file) {
  if (!file.isempty()) {
   
   stringbuffer requesturl = sessionutil.getrequesturl();
   int end = requesturl.indexof("/user/upload");
   string basepath = requesturl.substring(0, end);
   string savepath = basepath + "/static/img/logo/";
   // 获取文件名称,包含后缀
   string filename = file.getoriginalfilename();

   string savedbpath = savepath + filename;

   // 存放在这个路径下:该路径是该工程目录下的static文件下:(注:该文件可能需要自己创建)
   // 放在static下的原因是,存放的是静态文件资源,即通过浏览器输入本地服务器地址,加文件名时是可以访问到的
   string path = classutils.getdefaultclassloader().getresource("").getpath() + "static/img/logo/";

   // 该方法是对文件写入的封装,在util类中,导入该包即可使用,后面会给出方法
   try {
    fileutil.fileupload(file.getbytes(), path, filename);
    // 接着创建对应的实体类,将以下路径进行添加,然后通过数据库操作方法写入
    user user = sessionutil.getsessionuser();
    user.setlogo(savedbpath);
    user whereuser = new user();
    whereuser.setid(user.getid());
    confighelper.upate(user, "user", whereuser);
    map<string, object> map = new hashmap<>();
    map.put("msg", "头像修改成功");
    map.put("data", user);
    return resultdata.ok(map);
   } catch (ioexception e) {
    log.error("图片上传==》" + e.getmessage());
    e.printstacktrace();
    return resultdata.failed(e.getmessage());
   } catch (exception e) {
    log.error("图片上次==》" + e.getmessage());
    e.printstacktrace();
    return resultdata.failed(e.getmessage());
   }

  } else {
   return resultdata.failed("上传图片失败");
  }
 }

结束

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。