nodejs socket客户端 http上传

2012-05-18 13:59  3402人阅读  评论 (0)

今天要做个http上传的东东,以为是iphone段上传,虽然http上传我也大概了解,但是没有实质做过,给ios沟通以后告诉他上传协议以后,他怎么测试都不通过,郁闷,应该是我理解有误,然后就自己用nodejs写了一个,终于明白那里错了.还是对协议理解的不是很彻底,分隔字符串的前边也要加"--",这个之前没注意到...

这次主要是吧自己的代码分享给大家,让大家少走弯路.

nodejs socket客户端 http上传 upload.js

var net = require('net');
var client = net.connect(80, '20.t.yeamo.com', function() {
    console.log('client connected');

    var bodys = [];
    bodys.push('--998998');
    bodys.push('Content-Disposition: form-data; name="file"; filename="tt.txt"');
    bodys.push('Content-Type: text/plain');
    bodys.push('');
    bodys.push('ceshi xinxi, 还有中文!');
    bodys.push('--998998--\r\n');
    var body = bodys.join('\r\n');

    var heads = [];
    heads.push('POST /iphone_upload/upload.php HTTP/1.1');
    heads.push('Host: localhost');
    heads.push('Content-Type: multipart/form-data; boundary=998998');
    heads.push('Content-Length: '+Buffer.byteLength(body));
    var head = heads.join('\r\n');

    var request = head+'\r\n\r\n'+body;
    console.log(request+'\r\n');

    client.write(request);
});
client.on('data', function(data) {
    console.log(data.toString());
    client.end();
});
client.on('end', function() {
    console.log('client disconnected');
});

php 接收上传文件 upload.php

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    file_put_contents('log.txt', var_export($_SERVER, true)."\r\n\r\n", FILE_APPEND);
    file_put_contents('log.txt', var_export($_FILES, true)."\r\n\r\n", FILE_APPEND);

    $file = date('YmdHis').'.jpg';
    if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
        echo "upload ok! \r\n http://localhost/iphone_upload/$file";
    } else {
        echo "upload err!";
    }
    exit();
}
?>
<form enctype="multipart/form-data" action="upload.php" method="POST">
     Send this file: <input name="file" type="file" />
     <input type="submit" value="Send File" />
</form>
豫ICP备09035262号-1