vue裁剪并上传头像

之前,在用vue写一个上传头像的模块,里面需要对头像进行拖动裁剪设置,可是后台却跟我说他只要类似于input上传图片的内容。前端是没有办法操作本地图片的,一般也只能是传图片+裁剪的坐标给后台,除非用canvas来进行绘画裁剪然后再拿到裁剪后的base64图片地址,不断反复的转码再通过new的fromdata转成blob的格式,总之相当复杂。(github直接搜索vue-cropperjs),最终得以解决这个问题,相信大家一步一步看我如下的代码都是能看懂的。不懂的小伙伴可直接留言联系

html内容:

<div class="pic">
            <label>上传头像:</label>
            <input type="file" name="image" accept="image/*"
	     style="font-size: 1.2em; padding: 10px 0;"
	     @change="setImage"
	     />
            <p>支持JPG、PNG格式图片,不超过5M。拖拽或缩放图中的虚线方格可调整头像,注意右侧小头像预览效果。</p>
            <div style="width: 300px;height: 200px; display: inline-block;float: left;margin-top: 20px;margin-bottom: 90px;">
		        	<vue-cropper
			    	ref='cropper'
			    	:guides="true"
			    	:view-mode=2
			        :drag-mode="crop"
			        :auto-crop-area="0.5"
			        :min-container-width=250
			        :min-container-height=180
			        :background=true
			        :src="imgSrc"
			        alt="Source Image"
			        :cropmove="cropImage"
			        ></vue-cropper>  	
		        </div>
		        <h3>头像预览:</h3>
		        <img
				        :src="cropImg"
				        style="width: 100px; height: 100px; border: 1px solid gray;border-radius: 50%;margin-left: 142px;margin-top: 38px;"
				        alt="Cropped Image"
				    />
           
            <button type="button" @click="photoSubmit" class="btn_photo">保存</button>
          </div>
然后就是安装vue-cropperjs,直接在npm i vue-cropperjs -D

script

import VueCropper from 'vue-cropperjs';
export default {
	data(){
		return{
			cropImg:'../../../static/images/3_140818171934_4.jpg',
			crop:'',
			imgSrc:'../../../static/images/3_140818171934_4.jpg'
		}
	},
	methods:{
		setImage(e){
			const file = e.target.files[0];
                        if (!file.type.includes('image/')) {
                           alert('Please select an image file');
                         return;
                 }

        if (typeof FileReader === 'function') {
            const reader = new FileReader();
            reader.onload = (event) => {
                this.imgSrc = event.target.result;
                // rebuild cropperjs with the updated source
                this.$refs.cropper.replace(event.target.result);
            };
            reader.readAsDataURL(file);
        } else {
            alert('Sorry, FileReader API not supported');
        }
		},
		cropImage () {
	        // get image data for post processing, e.g. upload or setting image src
	        this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
	  },
	  photoSubmit(){
	  	//ajax传给后台
	  }
	},
  components: {
    
    
  }
}

最后把获取到的append过的fdss通过正常的input选择file发送给后台就ok了!因为之前项目写的早了,没有详细代码,只有截图,不过也很详细了,一般公司传图片的方式不是这种的,我们是碰到特殊特例了。不过也好,这样一来,完全用不到后台就能对图进行裁剪,哈哈。

猜你喜欢

转载自blog.csdn.net/qq_40513881/article/details/79828053
今日推荐