溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue-cropper組件如何實(shí)現(xiàn)圖片切割上傳

發(fā)布時(shí)間:2021-05-28 09:42:16 來源:億速云 閱讀:166 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下vue-cropper組件如何實(shí)現(xiàn)圖片切割上傳,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

vue-cropper在vue中的引入

1、組件內(nèi)引入

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"
      
      accept="image/png, image/jpeg, image/gif, image/jpg"
      @change="uploadImg($event, 1)"
    >
    <div >
      <div class="show-preview" :>
        <div : class="preview" >
          <img :src="previews.url" :>
        </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, //剪切后的圖片質(zhì)量(0.1-1)
        full: false, //輸出原圖比例截圖 props名full
        outputType: "png",
        canMove: true,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        autoCropWidth: 40,
        autoCropHeight: 40,
        fixedBox: true
      }
    };
  },
  methods: {
    //上傳圖片(點(diǎn)擊上傳按鈕)
    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轉(zhuǎn)化為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;
        }
      };
      // 轉(zhuǎn)化為base64
      // reader.readAsDataURL(file)
      // 轉(zhuǎn)化為blob
      reader.readAsArrayBuffer(file);
    },
    show() {
      this.dialogFormVisible = true;
    },
    // 實(shí)時(shí)預(yù)覽函數(shù)
    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;
    }
}

發(fā)送請求的時(shí)候配置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;

   // 存放在這個(gè)路徑下:該路徑是該工程目錄下的static文件下:(注:該文件可能需要自己創(chuàng)建)
   // 放在static下的原因是,存放的是靜態(tài)文件資源,即通過瀏覽器輸入本地服務(wù)器地址,加文件名時(shí)是可以訪問到的
   String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/img/logo/";

   // 該方法是對文件寫入的封裝,在util類中,導(dǎo)入該包即可使用,后面會(huì)給出方法
   try {
    FileUtil.fileupload(file.getBytes(), path, fileName);
    // 接著創(chuàng)建對應(yīng)的實(shí)體類,將以下路徑進(jìn)行添加,然后通過數(shù)據(jù)庫操作方法寫入
    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("上傳圖片失敗");
  }
 }

以上是“vue-cropper組件如何實(shí)現(xiàn)圖片切割上傳”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI