var fs = require("fs"); var http = require('http'); function PostFileToServer(sFileName, data, callback) { var boundary = "NODEJSPOSTFILE-" + (Math.random() * 9007199254740992).toString(36); var sHeader = "--" + boundary + " "; sHeader += "Content-Disposition: form-data; name="fileName"; filename="" + sFileName + "" "; sHeader += "Content-Type: application/octet-stream "; var sEndData = " --" + boundary + "-- "; var options = { hostname: "127.0.0.1", port : 3031, path : "/cgi-bin/upload?action=uploadFile&newname=my.jpg", method : 'POST' }; var httpreq = http.request(options, function (httpres) { httpres.on('data', function (dataResponse) { var response = JSON.parse(dataResponse); console.log(response.md5); console.log(response.name); }); }); httpreq.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary + ''); httpreq.setHeader('Content-Length', Buffer.byteLength(sHeader) + data.length + Buffer.byteLength(sEndData)); httpreq.on('error', function(e) { console.log('problem with request: ' + e.message); callback(e); return; }); httpreq.write(sHeader); httpreq.write(data); httpreq.write(sEndData); httpreq.end(); } fs.readFile('1.jpg', function (err, data) { if (err) throw err; console.log(data.length); PostFileToServer("1.jpg", data, function(){ console.log("call back"); }); });
{ fileName: { domain: null, _events: {}, _maxListeners: undefined, size: 595284, path: 'tmp\upload_ba227eaf1015fda43ea4a218b2161748', name: '1.jpg', type: 'application/octet-stream', hash: null, lastModifiedDate: Sun Mar 08 2015 14:34:18 GMT+0800 (中国标准时间), _writeStream: { _writableState: [Object], writable: true, domain: null, _events: {}, _maxListeners: undefined, path: 'tmp\upload_ba227eaf1015fda43ea4a218b2161748', fd: null, flags: 'w', mode: 438, start: undefined, pos: undefined, bytesWritten: 595284, closed: true } } }