前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于vue的图片裁剪插件vue-cropper ,上传图片到腾讯云存储

基于vue的图片裁剪插件vue-cropper ,上传图片到腾讯云存储

作者头像
〆 千寻、
发布2020-03-11 18:23:00
4.2K0
发布2020-03-11 18:23:00
举报
文章被收录于专栏:技术分享文章技术分享文章

网上找了点教程,结合之前框架里就有的修改了一下,没做细节优化处理

demo 16:9的尺寸,自己可以修改

基于vue的图片裁剪插件vue-cropper ,上传图片到腾讯云存储
基于vue的图片裁剪插件vue-cropper ,上传图片到腾讯云存储

步骤:

npm install vue-cropper

代码语言:javascript
复制
组件内使用
import { VueCropper }  from 'vue-cropper' 
components: {
  VueCropper,
},
代码语言:javascript
复制
<!--截图start-->
<CutImages ref="cutStatus"  :option="option" v-on:updateBaseimg="updateBaseimg"/>
<!--截图end-->

使用方法 具体看下面

代码语言:javascript
复制
<template>
    <div>
     <div class="intro-upload-img">
                                    <a href="javascript:;" class="file">
                                        <div v-if="!moreSet.imageUrl">上传</div>
                                        <div v-if="moreSet.imageUrl" class="upload-img-url">
                                            <img :src="moreSet.imageUrl"/>
                                        </div>
                                        <input type="file" @change="fileUpload($event)">
                                    </a>
                                </div>
        <CutImages ref="cutStatus"  :option="option" v-on:updateBaseimg="updateBaseimg"/>
        <!--截图end-->
    </div>
</template>

<script>
    import CutImages from "@/components/cut";
    import COS from 'cos-js-sdk-v5' //存储桶
    export default {
        components: {
           CutImages
        },
        name: "index",
        data() {
            return {
                showCut: false,//截图插件的弹窗
                option: {   //配置文件
                    img: '',
                    info: true,
                    size: 1,
                    outputType: 'jpeg',
                    canScale: true,
                    autoCrop: true,
                    // 只有自动截图开启 宽度高度才生效
                    autoCropWidth: 300,
                    autoCropHeight: 250,
                    fixed: true,
                    // 真实的输出宽高
                    infoTrue: true,
                    fixedNumber: [16, 9]
                },
                //更多设置
                moreSet: {
                    imageUrl: '',
                },
                cosData: {}, //存储桶
                classid: '',//课堂id
            }
        }, created() {
       
        },
        methods: {
            /**
             * 获取截图的文件对象
             * 进行图片上传到腾讯云
             * **/
            updateBaseimg(event) {
                let _this =this
                _this.showCut = false //隐藏截图插件
                if (!event) return
                _this.initCallBack()
                const time = _this.getTime()
                this.cosData.putObject({
                    Bucket:bucket, /* 必须 */
                    Region:region, /* 必须 */
                    Key: 'classroom/' + time + '/' + event.name, /* 必须 */
                    StorageClass: 'STANDARD',
                    Body: event, // 上传文件对象
                    onProgress: function (progressData) {
                        // console.log(JSON.stringify(progressData))
                    }
                }, function (err, data) {
                    _this.moreSet.imageUrl = 'http://' + data.Location
                });
            },
        
            /**
             * 设置图片上传
             * 获取文件对象,调用截图插件
             * **/
            fileUpload(event) {
                let _this = this
                _this.$refs.cutStatus.getFileInfo(event)
            },
        }
    }
</script>
<style lang="less" scoped>
 
</style>

组件:

代码语言:javascript
复制
<template>
    <div class>
        <el-dialog title="编辑图片" :visible.sync="showCut" :before-close="close" :width="'832px'"
                   :close-on-click-modal="false">
            <div>
                <div style="width: 800px;height: 600px">
                    <vueCropper ref="cropper" :img="option.img " :outputSize="option.size"
                                :outputType="option.outputType"
                                :info="option.info" :canScale="option.canScale" :autoCrop="option.autoCrop"
                                :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight"
                                :fixed="option.fixed"
                                :fixedNumber="option.fixedNumber" :enlarge="4"></vueCropper>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="close" size="small">取 消</el-button>
                <el-button type="primary" @click="submit" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {VueCropper} from "vue-cropper";
    export default {
        components: {VueCropper},
        props: ["option"],
        data() {
            return {
                filename:'',  //图片名称
                showCut:false,//弹窗
            };
        },
        computed: {},
        watch: {},
        methods: {
            /**
             * 获取文件对象
             * **/
            getFileInfo(e) {
                this.showCut = true
                this.option.img = ''
                this.filename = e.target.files[0].name
                var file = e.target.files[0]
                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
                    data = e.target.result
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result
                    }
                    this.option.img = data
                }
                // 转化为base64
                // reader.readAsDataURL(file)
                // 转化为blobcs
                reader.readAsArrayBuffer(file)
            },
            /**
             * 提交
             * data:是文件对象
             * dataURLtoFile:base64转文件
             * **/
            submit() {
                this.$refs.cropper.getCropData((data) => {
                    const info  = this.dataURLtoFile(data,this.filename)
                    this.$emit("updateBaseimg",info);
                    this.showCut = false
                })
            },
            /**
             * base64转文件
             * @param dataurl:图片的链接或者base64,filename:图片的名称
             * **/
            dataURLtoFile(dataurl, filename) {
                var arr = dataurl.split(","),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, {
                    type: mime
                });
            },
            /**
             * 关闭弹窗
             * **/
            close() {
                this.showCut = false
                this.option.img = ''
            },

            // getBase64() {
            //     this.$refs.cropper.getCropData(data => {
            //         const formData = new FormData();
            //         formData.append("file", this.dataURLtoFile(data, "123.jpeg"));
            //         formData.append("category", this.option.category);
            //         fileupload(formData).then(res => {
            //             this.$emit("updateBaseimg", {
            //                 url: res,
            //                 key: this.option.key
            //             });
            //             this.$notify({
            //                 type: "success",
            //                 message: "上传成功",
            //                 title: "提示"
            //             });
            //         });
            //     });
            // },
        },
        created() {
        },
        mounted() {
        }
    };
</script>
<style lang='less' scoped>
</style>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年1月13日1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档