CocosCreator发布华为快游戏——上传日志文件到服务器、截图保存

因为华为快游戏好像是没有像微信一样提供uploadFile的接口(快应用有。。。),所以要自己重新写一个xhr发的过程,用HelloWorld写了个小demo做记录阿巴阿巴;

另一个是截图保存的,因为canvas.toTempFilePath也不支持,so。。。

cc.Class({
    extends: cc.Component,

    properties: {
        label: {
            default: null,
            type: cc.Label
        },
        // defaults, set visually when attaching this script to the Canvas
        text: 'Hello, World!'
    },

    // use this for initialization
    onLoad: function () {
        this.label.string = this.text;

        var url = "https://xyx.zonst.com/update/wx/user/txt";

        function FormData(data, rs) {
            return ((function (data, rs) {
                let data_string = '\r\n'
                for (let [k, v] of Object.entries(data)) {
                    if (k === "file") {
                        //data_string += '------WebKitFormBoundary'+rs+'--'
                        data_string +=
                            '------WebKitFormBoundary' + rs + '\r\nContent-Disposition: form-data; name="' + k + '"; filename="hwlog.txt"\r\nContent-Type: "text/plain"\r\n\r\n' + v + '\r\n';
                    } else if (({}).toString.call(v) === '[object Array]') {
                        for (let el of v) {
                            data_string +=
                                '------WebKitFormBoundary' + rs + '\r\nContent-Disposition: form-data; name="' + k + '"\r\n\r\n' + el + '\r\n';
                        }
                    } else {
                        data_string +=
                            '------WebKitFormBoundary' + rs + '\r\nContent-Disposition: form-data; name="' + k + '"\r\n\r\n' + v + '\r\n';
                    }
                }
                data_string += '------WebKitFormBoundary' + rs + '--'
                return data_string;

            })(data, rs));
        }

        function randomString32(len) {
            const loopn = len || 32;
            const c = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            let res = '';
            for (let i = 0; i < loopn; i++) {
                res += c.charAt(Math.floor(Math.random() * c.length));
            }
            return res;
        }

        var logs = "测试123";
        try {
            console.log("尝试上报错误日志1.3");
            var rs = randomString32(16);
            var fd = FormData({
                file: logs,
            }, rs, logs);

            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=----WebKitFormBoundary' + rs);
            xhr.onreadystatechange = function () {
                console.log("状态变更", xhr.readyState)
                if (xhr.readyState == 4) {
                    console.log("状态码", xhr.status)
                    if (xhr.status >= 200 && xhr.status < 400) {
                        var response = xhr.responseText;
                        console.log("httpPost[" + url + "] status:", xhr.status, "回复消息:", response);
                    } else {
                        console.warn("httpPost[" + url + "] error->status:" + xhr.status);
                    }
                }
            };
            //超时回调记录
            xhr.ontimeout = function () {
                console.log("httpPost timeout url:" + url);
            }

            xhr.send(fd);
            console.log("尝试上报错误日志2");
        } catch (e) { console.log(e) }

        console.log("尝试上报错误日志3");

    },

    // called every frame
    update: function (dt) {
        //this.label.string = dt;
    },

    captureScreenToPhoto: function (callback) {
        var camera = cc.Camera.main;
        cc.log("获取主相机")
        var texture = new cc.RenderTexture();
        texture.initWithSize(Math.ceil(cc.winSize.width), Math.ceil(cc.winSize.height));
        camera.targetTexture = texture;
        camera.render();
        camera.targetTexture = null;
        cc.log("渲染到相机")
        var data = texture.readPixels();
        cc.log("数据", data.length);
        var udata = new Uint8Array(data);
        try {
            hbs.saveImageTemp({
                data: udata,
                width: Math.ceil(cc.winSize.width),
                height: Math.ceil(cc.winSize.height),
                fileType: "jpg",
                reverse: true,
                success: (res) => {
                    cc.log("暂存图片", JSON.stringify(res));
                    hbs.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: (res) => {
                            cc.log("保存图片到本地", res.tempFilePath);
                        },
                        fail: (err) => {
                            cc.error("保存失败", JSON.stringify(err));
                        },
                    });
                },
                fail: (err) => {
                    cc.error("失败", JSON.stringify(err));
                },
                complete: (res) => {
                    cc.log("执行完成")
                }
            });
        } catch (err) {
            cc.error(JSON.stringify(err));
        }
        cc.log("完成")
    },

    savePhoto: function (callback) {
        cc.log("尝试保存图片")
        if (!hbs.saveImageToPhotosAlbum) {
            cc.log("不能保存图片到本地")
            hbs.showModal({
                title: '提示',
                content: '当前应用版本过低,无法使用该功能,请升级到最新版本后重试。'
            })
            if (callback) {
                callback();
            }
            return;
        }

        cc.log("尝试保存图片1")
        var that = this;
        hbs.getSetting({
            success(res) {
                cc.log(JSON.stringify(res));
                if (res.authSetting["writePhotosAlbum"]) {
                    that.captureScreenToPhoto(callback);
                } else {
                    that.authorize(
                        "writePhotosAlbum",
                        "请前往设置界面,\n授权相册访问权限",
                        () => {
                            that.captureScreenToPhoto(callback);
                        }
                    );
                }
            }
        })
    },

    authorize: function (scope, message, callback, errorMessage) {
        cc.log("尝试授权保存图片到相册", scope);
        var params = {};
        if (scope == "userInfo") {
            params = {
                appid: APP_ID,
                type: "token",
                scope: "userInfo",
            }
        }
        hbs.authorize({
            scope: scope,
            params: params,
            success() {
                cc.log("申请权限成功");
                callback();
            },
            fail(res) {
                cc.log("======>hbs.authorize fail", res);
                hbs.getSetting({
                    success(res) {
                        cc.log("hbs.getSetting-->", res);
                        if (res.authSetting[scope] != null) {
                            hbs.openSetting({
                                success(res) {
                                    if (!res.authSetting[scope]) {
                                        return;
                                    }
                                    if (msgbox && msgbox.isValid) {
                                        msgbox.node.destroy();
                                    }
                                    callback()
                                }
                            })
                        }
                    }
                })
            },
        })
    },
});

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值