cocos creator get/post请求与文件下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/themagickeyjianan/article/details/86018191

1)http模块

var http = {

    /**
     * 功能:get请求
     * @param url
     * @param path
     * @param params
     * @param cb
     */
    get: function (url, path, params, cb) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if(params){
            requestURL = requestURL + "?" + params;
        }

        xhr.open("GET", requestURL, true);

        if(cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
        }
        
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)){
                // console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                try{
                    var ret = xhr.responseText;
                    if(cb){
                        cb(null, ret);
                    }
                }catch (e) {
                    console.log("err:" + e);
                    cb(e, null);
                }
            }
        }

        xhr.send();
        return xhr;
    },

    /**
     * 功能:post请求
     *     1)与get区别就是post能带数据body,其余均一样
     * @param url
     * @param path
     * @param params
     * @param body
     * @param cb
     */
    post: function (url, path, params, body, cb) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if(params){
            requestURL = requestURL + "?" + params;
        }

        // true代表异步
        xhr.open("POST", requestURL, true);

        if(cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
        }

        if(body){
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }

        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)){
                console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                try{
                    var ret = xhr.responseText;
                    if(cb){
                        cb(null, ret);
                    }
                }catch (e) {
                    console.log("err:" + e);
                    cb(e, null);
                }
            }
        }

        //
        if(body){
            xhr.send(body);
        }

        return xhr;
    },

    /**
     * 功能:下载
     * @param url
     * @param path
     * @param params
     * @param cb
     */
    download: function (url, path, params, cb) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 5000;
        var requestURL = url + path;
        if(params){
            requestURL = requestURL + "?" + params;
        }

        xhr.responseType = "arraybuffer";
        xhr.open("GET", requestURL, true);
        if(cc.sys.isNative){
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
        }

        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)){
                var buffer = xhr.response;

                //
                var data = new Uint8Array(buffer);

                cb(null, data);
            }
        }

        xhr.send();
        return xhr;
    }
    
}

module.exports = http;

2)

var http = require("./http.js");

cc.Class({
    extends: cc.Component,

    properties: {

    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

    },

    /**
     * 功能:get请求
     */
    on_get_click: function () {
        http.get("http://127.0.0.1:6080", "/get", "uname=jianan&phone=123456", function (err, ret) {
            if(err){
                console.log(err);
                return;
            }

            console.log(ret);
        });
    },

    /**
     * 功能:通过post上传文件
     */
    on_upload_click: function () {

        var path = jsb.fileUtils.getWritablePath();
        var fileData = jsb.fileUtils.getDataFromFile(path + "headImg.png");

        http.post("http://127.0.0.1:6080", "/upload", "name=upload.png", fileData, function (err, ret) {
            if(err){
                console.log(err);
                return;
            }

            console.log(ret);
        });

    },

    /**
     * 功能:get请求下载文件
     */
    on_download_bin_click: function () {
        http.download("http://127.0.0.1:6080", "/download", "name=upload", function (err, data) {
           var path = jsb.fileUtils.getWritablePath() + "/download.png";
           jsb.fileUtils.writeDataToFile(data, path);
        });
    }

    // update (dt) {},
});

3)webserver.js

var express = require("express");
var app = express();
var path = require("path");
var fs = require("fs");

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use(express.static(path.join(process.cwd(), "www_root")));

//
app.get("/get", function (req, res) {
    console.log(req.query);
    res.send("hello world");
});

//
app.post("/upload", function (req, res) {
    req.now_len = 0;

    var file_name = "./upload/" + req.query.name;

    var fd = fs.openSync(file_name, "w");
    req.on("data", function (data) {
        req.now_len += data.length;
        fs.write(fd, data, 0, data.length);
    });
    
    req.on("end", function () {
        console.log("upload file " + req.query.name + " success");
        fs.close(fd);
        res.send("ok");
    });
});

//
app.get("/download", function (req, res) {
    var file_name = "./upload/" + req.query.name + ".png";
    console.log(file_name);
    fs.readFile(file_name, function (err, data) {
        if(err){
            res.send("file err");
            return;
        }

        res.send(data);
    });

});

//
app.listen(6080);

console.log("webserver start!!!");



猜你喜欢

转载自blog.csdn.net/themagickeyjianan/article/details/86018191