返回列表

Node.js POST File to Server and Receive File

默认分类 2014/11/09 01:51

发送文件 send.js:

'use strict';
var fs = require('fs');
var formData = require('form-data');

var form = new formData();

form.append('upload', fs.createReadStream(__dirname + '/dir/3.txt'));

form.submit({
    host: 'localhost',
    port: '8888',
    path: '/upload'
}, function (err, res) {
    console.log(res.statusCode);
    if (err) {
        return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:');
});

或者

'use strict';
var request = require('request');
var fs = require('fs');

var formData = {
    upload: fs.createReadStream(__dirname + '/dir/2.txt')
};

request.post({
    url: 'http://localhost:8888/upload',
    formData: formData
}, function optionalCallback(err, httpResponse, body) {
    if (err) {
        return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:', body);
});

或者

'use strict';
var fs = require('fs');
var formData = require('form-data');
var http = require('http');

var form = new formData();

form.append('upload', fs.createReadStream(__dirname + '/dir/3.txt'));

var request = http.request({
    method: 'post',
    host: 'localhost',
    port: '8888',
    path: '/upload',
    headers: form.getHeaders()
});

form.pipe(request);

request.on('response', function (res) {
    console.log(res.statusCode);
});

接收文件receive.js

'use strict';

var fstream = require('fstream');
var fs = require('fs');
var path = require('path');

var formidable = require('formidable'),
    http = require('http');
http.createServer(function (req, res) {
    if (req.url == '/upload' && req.method.toLowerCase() == 'post') { // parse a file upload     
        var form = new formidable.IncomingForm();
        form.uploadDir = 'dir';
        form.parse(req, function (err, fields, files) {
            if (files && files.upload) {
                fstream.Reader({
                    'path': path.resolve(files.upload.path)
                })
                    .pipe(fstream.Writer({
                        'path': path.resolve(files.upload.name)
                    }))
                    .on('close', function () {
                        // delete tmp file
                        fs.unlink(path.resolve(files.upload.path));
                        res.end(' uploaded');
                    });
            }
            else {
                res.end(' uploaded none');
            }
        });
        return;
    } // show a file upload form   

    res.writeHead(200, {
        'content-type': 'text/html'
    });
    res.end(
        '<form action="/upload" enctype="multipart/form-data" method="post">' +
        '   <input type="file" name="upload" multiple="multiple"><br>' +
        '   <input type="submit" value="Upload">' +
        '</form>'
    );
}).listen(8888);

console.log('Server is listen at http://localhost:8888');