Ext js 实现图片上传

一、前言

  由于在ext中调用jquery不好搞,所以我们使用iframe的方式来引用插件。

使用资源:

   jQuery插件库中q22ImgCropping:http://www.jq22.com/jquery-info18167

完成后的效果展示:

二、实现代码

  iframe中的代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>基于cropper.js的图片裁剪</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="format-detection" content="telephone=no">

    <link rel="stylesheet" href="../libs/jsCropper/css/cropper.min.css">
    <link rel="stylesheet" href="../libs/jsCropper/css/ImgCropping.css">

</head>

<body>

    <!--图片裁剪框 start-->
    <div class="tailoring-container">
        <div onclick="closeTailor(this)"></div>
        <div class="tailoring-content">
            <div class="tailoring-content-one">
                <label title="上传图片" for="chooseImg" class="l-btn choose-btn">
                    <input type="file" accept="image/jpg,image/jpeg,image/png" name="file" id="chooseImg" class="hidden"
                        onchange="selectImg(this)">
                    选择图片
                </label>
                <!-- <div class="close-tailoring"  onclick="closeTailor(this)">×</div> -->
            </div>
            <div class="tailoring-content-two">
                <div class="tailoring-box-parcel">
                    <img id="tailoringImg">
                </div>
                <div class="preview-box-parcel">
                    <p>图片预览:</p>
                    <div class="square previewImg"></div>
                    <div class="circular previewImg"></div>
                </div>
            </div>
        </div>
    </div>
    <!--图片裁剪框 end-->


    <script src="../libs/jquery/jquery-3.3.1.min.js"></script>
    <script src="../libs/jsCropper/js/cropper.min.js"></script>
    <script>
        //图像上传
        function selectImg(file) {
            if (!file.files || !file.files[0]) {
                return;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                var replaceSrc = evt.target.result;
                //更换cropper的图片
                $('#tailoringImg').cropper('replace', replaceSrc, false);//默认false,适应高度,不失真
                setButtonEnable && setButtonEnable();
            }
            reader.readAsDataURL(file.files[0]);
        }
        //cropper图片裁剪
        $('#tailoringImg').cropper({
            aspectRatio: 1 / 1,//默认比例
            preview: '.previewImg',//预览视图
            guides: false,  //裁剪框的虚线(九宫格)
            autoCropArea: 0.5,  //0-1之间的数值,定义自动剪裁区域的大小,默认0.8
            movable: false, //是否允许移动图片
            dragCrop: true,  //是否允许移除当前的剪裁框,并通过拖动来新建一个剪裁框区域
            movable: true,  //是否允许移动剪裁框
            resizable: true,  //是否允许改变裁剪框的大小
            zoomable: false,  //是否允许缩放图片大小
            mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
            touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
            rotatable: true,  //是否允许旋转图片
            crop: function (e) {
                // 输出结果数据裁剪图像。
            }
        });

        //旋转
        function rotate() {
            $('#tailoringImg').cropper("rotate", 45);
        }

        //复位
        function reset() {
            $('#tailoringImg').cropper("reset");
        }

        //换向
        function scaleX(param) {
            if (param) {
                $('#tailoringImg').cropper("scaleX", -1);
            } else {
                $('#tailoringImg').cropper("scaleX", 1);
            }
        }

        
        //裁剪后的处理
        function sureCut(){
            if ($("#tailoringImg").attr("src") == null) {
                return false;
            } else {
                var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
                var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
                $("#finalImg").prop("src", base64url);//显示为图片的形式

                //此处加回调函数
                setBase64Image&&setBase64Image(base64url);
            }
        }
    </script>

</body>

</html>

extjs的代码

Ext.define('xxxxx.abp.account.view.ChangeAvatar', {
    extend: 'Ext.window.Window',
    controller: 'abp.account.changeavatar',

    listeners: {
        close: function () {
            location.hash = 'o';
        }
    },

    layout: 'fit',
    closeAction: 'close',
    title: '修改头像',
    frame: true,
    modal: true,
    waitMsgTarget: true,
    animateTarget: true,
     780,
    height: 600,
    fileUpload: false,
    items: [{
        xtype: 'form',
        defaultType: 'textfield',
        defaultButton: 'btnSubmit',

        submitProperty: 'data', //viewmodel中提交到服务器数据的属性名
        useViewModel: false, //使用mvvm模式,不调用填充表单的方法
        modelValidation: false, //是否使用viewmodel中带的验证
        layout: 'fit',

        items: [
            {
                xtype: "panel",
                name: 'upAvatar',
                layout: 'fit',
                listeners: {
                    afterrender: function () {
                        var win = this.up('window');
                        window.avatarCallback = function (cw) {
                            var frame = cw.contentWindow;
                            win.frame = frame;
                            frame.setButtonEnable = function () {
                                win.setButtonDisable(win,false)
                            }
                            frame.setButtonDisable = function () {
                                win.setButtonDisable(win,true)
                            }

                            frame.setButtonDisable = function () {
                                alert(32)
                            }

                            frame.setBase64Image = function (option) { 
                                if (option.length <10) return;
                                win.down('[name=Base64File]').setValue(option);
                            }
                        };
                        this.setHtml('<iframe src="res/UploadAvatar.html" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" style="100%;height:100%;" onload="avatarCallback(this)" />');
                    }
                }
            }, {
                xtype: 'textfield',
                name: 'Base64File',
                hidden:true
            }
        ],


        buttons: [
            {
                text: '旋转',
                handler: 'rotate',
                disabled: true,
            },
            {
                text: '复位',
                handler: 'reset',
                disabled: true,
            },
            {
                text: '正向换向',
                handler: 'scaleX',
                name:"scaleX",
                option:true,
                disabled: true,
            },
            {
                text: '逆向换向',
                handler: 'scaleX',
                name:"scaleY",
                option:false,
                disabled: true,
            }, "->",
            {
                text: l('Cancel'),
                handler: 'closeForm',
                iconCls: 'fa fa-window-close',
            },
            {
                text: l('Save'),
                handler: 'saveForm',
                iconCls: 'fa fa-save',
                reference: 'btnSubmit',
                disabled: true,
            }],

        defaults: {
            anchor: '100%',
            labelWidth: 80
        },
        getSubmitData:function(){
            var me = this;
            return {
                fileName: "1213165",
                base64:me.down("[name=Base64File]").value
            }
        } 
        

    }],
    setButtonDisable: function (sender, param) {
        sender.down('[handler=rotate]').setDisabled(param);
        sender.down('[handler=reset]').setDisabled(param);
        sender.down('[name=scaleX]').setDisabled(param);
        sender.down('[name=scaleY]').setDisabled(param);
        sender.down('[handler=saveForm]').setDisabled(param)
    }
});

controllere代码

Ext.define('xxxxxxx.abp.account.view.ChangeAvatarController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.abp.account.changeavatar',
    config: {},
    /**
     * Called when the view is created
     */
    init: function () { },

    saveForm: function (sender, record) { //保存表单
        var me = this;
        
        //图片裁剪
        me.getView().frame.sureCut();

        var form = sender.up('form');
        
        return Eui.ext.Form.submit(form, Api.app.profile.uploadProfilePictureBase64, 10, function (response) {
            Ext.toast(l('OperateSuccess'));
            form.reset();
            $(".avatar").attr("src", HOST_URL + "Profile/GetProfilePictureById?profilePictureId=" + abp.loginInfo.user.id + "&t=" + Math.random())
            form.up('window').close();
        });
    },
    closeForm: function (sender, record) { //关闭表单
        sender.up('window').close();
    },

    /**
     * 旋转
     * @param {win} sender 
     */
    rotate: function (sender) { 
        this.getView().frame.rotate();
    },

    /**
     * 复位
     * @param {*} sender 
     */
    reset: function (sender) { 
        this.getView().frame.reset();
    },

    /**
     * 逆向
     * @param {*} sender 
     */
    scaleX: function (sender) { 
        var param = sender.option;
        this.getView().frame.scaleX(param);
    }
});
原文地址:https://www.cnblogs.com/gzbit-zxx/p/12867645.html