Show toolbar
顯示具有 File 標籤的文章。 顯示所有文章
顯示具有 File 標籤的文章。 顯示所有文章

2014年5月5日 星期一

AJAX send POST, GET, FILE and get JSON

標題:AJAX送出POST/GET/FILE並取得JSON資訊
HTML (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send Post</title>
<script type="text/javascript">
var sendPost = function() {
    this.current = null;
    this.queue = [];
};
sendPost.prototype.request = function(q) {
    var self = this;
    var query = [];
    var formdata = new FormData(document.createElement('form'));
    for(key in q.params) {
        switch(q.params[key].constructor) {
            case Number:
                formdata.append(key, q.params[key]);
                break;
            case String:
                formdata.append(key, q.params[key]);
                break;
            case Array:
                for(var i=0;i<q.params[key].length;i++) {
                    formdata.append(key, q.params[key][i]);
                }
                break;
            default:
                var type = q.params[key].getAttribute("type");
                if(type == 'file') {
                    for(var i=0;i<q.params[key].files.length;i++) {
                        formdata.append(key, q.params[key].files[i]);
                    }
                } else if(type=='password'||type=='text'||type=='hidden') {
                    formdata.append(key, q.params[key].value);
                }
                break;
        }
    }
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('POST', q.url, true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == '200') {
            self.current.load(JSON.parse(xobj.responseText));
            self.action();
        }
    };
    this.queue.push({
        xobj : xobj,
        formdata : formdata,
        load : q.load
    });
    if(!this.current) this.action();
};
sendPost.prototype.action = function() {
    this.current = null;
    if(this.queue.length) {
        this.current = this.queue.shift();
        this.current.xobj.send(this.current.formdata);
    }
};
window.onload = function() {
    document.getElementById('btn').onclick = function() {
        var mySendPost = new sendPost();
        mySendPost.request({
            url : '/test?method=work',
            params : {
                'file' : document.getElementById('myfile'),
                'name' : document.getElementById('myname'),
                'password' : document.getElementById('mypassword'),
                'hidden' : document.getElementById('myhidden'),
                'str' : 'Hello',
                'num1' : 20,
                'num2' : new Array(30, 40)
            },
            load : function(data) {
                document.getElementById('output').innerHTML = JSON.stringify(data, null, 2);
            }
        });
    };
};
</script>
</head>
<body>
<input type="file" id="myfile" multiple="multiple" /><br />
<input type="text" id="myname" value="QQBoxy" /><br />
<input type="password" id="mypassword" value="abcd1234" /><br />
<input type="hidden" id="myhidden" value="HideBoxy" />
<button id="btn">Button</button><br />
<pre id="output"></pre>
</body>
</html>

Node.js (main.js):
var express    = require('./node_modules/express'),
    multiparty = require('./node_modules/multiparty'),
    multipart  = require('./node_modules/connect-multiparty');

var port = 1337;
var app = express();
var multipartMiddleware = multipart();

app.listen(port);
app.use('/', express.static(__dirname + '/html/'));

app.post('/test', multipartMiddleware, function(req, res) {
    res.set('Content-Type', 'application/json;charset=utf-8');
    var json = {
        'get' : req.query,
        'post' : req.body,
        'file' : req.files
    };
    //console.log(JSON.stringify(json, null, 2)); //測試用
    res.send(JSON.stringify(json, null, 2));
});

console.log("Start express server on port %s", port);

範例結果:


說明:
使用FormData方式傳送GET、POST、FILE資訊,
並且建立簡單Node.js伺服器傳回之JSON資訊進行測試,
關於Node.js接收檔案的方法請參考這篇。
Google Chrome 34.0.1847.131 m、Firefox 27.0.1、IE11 測試可正常執行。

2013年7月15日 星期一

Drag to read the file

標題:拖曳方式讀取檔案
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <fstream> //ifstream
#include <sstream> //getline
using namespace std;

int main(const int argc, char *argv[])
{
    /*int i = 0;
    cout << "argc: " << argc << endl;
    for(i=0;i<argc;i++)
    {
        cout << "*argv[" << i << "]: " << argv[i] << endl;
    }*/

    //Path Convert
    char pathChar[1024];
    string pathString = "";
    strcpy(pathChar, argv[1]); //Pointer to Char
    pathString.assign(pathChar); //Char to String

    //ReadFile
    string lines = "";
    ifstream File(pathString);
    if (File.is_open()) //Check File
    {
        while(File.good())
        {
            getline(File, lines);
            cout << lines << endl;
        }
        File.close();
    }

    system("pause");
    return 0;
}
Batch (Start.bat):


說明:
將檔案拖曳至exe執行檔,並藉由argc、argv取得路徑,轉換路徑變數型態後進行讀檔動作。
Batch檔是用來測試多行參數的讀取,須放在與執行檔相同之目錄。

2013年7月8日 星期一

Two ways to Read and Write Files

標題:C/C++兩種讀取文字檔的方法
VC++ (main.cpp):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
//#include <iomanip>
//setprecision(4) "3.1415"
//setfill('Q') "QQ123"
//setw(5) "  123"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 0, j = 0;
    const char *filePath = "pi.xls";

    remove(filePath); //Delete File
    
    //VC++ -----------------------------------------------------

    //Write File
    ofstream outputFile(filePath, fstream::app); //fstream::out fstream::app
    if (outputFile.is_open()) //Check File
    {
        for(j=1;j<10;j++)
        {
            for(i=1;i<10;i++)
            {
                outputFile << i << "*" << j << "=" << i*j << "\t";
            }
            outputFile << endl;
        }
        outputFile.close();
    }

    //Read File
    string lines = "";
    ifstream inputFile(filePath);
    if (inputFile.is_open()) //Check File
    {
        while(inputFile.good())
        {
            getline(inputFile, lines);
            cout << lines << endl;
        }
        inputFile.close();
    }

    //Standard C -----------------------------------------------------

    //Write File
    FILE *writeFile = fopen(filePath, "a");
    if (writeFile) { //Check File
        for(j=1;j<10;j++)
        {
            for(i=1;i<10;i++)
            {
                fprintf(writeFile, "%d*%d=%d\t", i, j, i*j);
            }
            fprintf(writeFile, "\n");
        }
        fclose(writeFile);
    }
    
    //Read File
    char line[100] = ""; // Light!!
    FILE *readFile = fopen(filePath, "r");
    if (readFile) { //Check File
        while(fgets(line, sizeof(line), readFile))
        {
            printf("%s", line);
        }
        fclose(readFile);
    }

    return 0;
}

說明:
使用fstream的方法讀寫檔案,以及使用C的fopen讀寫檔案的方法。