Created
September 22, 2011 12:34
-
-
Save jinwei233/1234655 to your computer and use it in GitHub Desktop.
上传文件至PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var fs = require('fs'); | |
function EncodeFieldPart(boundary,name,value) { | |
var return_part = "--" + boundary + "\r\n"; | |
return_part += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"; | |
return_part += value + "\r\n"; | |
return return_part; | |
} | |
function EncodeFilePart(boundary,type,name,filename) { | |
var return_part = "--" + boundary + "\r\n"; | |
return_part += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n"; | |
return_part += "Content-Type: " + type + "\r\n\r\n"; | |
return return_part; | |
} | |
// Encode functions from above | |
function PreparePost() { | |
var boundary = Math.random(); | |
var post_data = []; | |
post_data.push(new Buffer(EncodeFieldPart(boundary, 'field1', 'value1'), 'ascii')); | |
post_data.push(new Buffer(EncodeFieldPart(boundary, 'field2', 'value2'), 'ascii')); | |
post_data.push(new Buffer(EncodeFilePart(boundary, 'text/plain', 'textfile', 'test.txt'), 'ascii')); | |
var file_reader = fs.createReadStream('test.txt', {encoding: 'utf8'}); | |
var file_contents = ''; | |
file_reader.on('data', function(data){ | |
file_contents += data; | |
}); | |
file_reader.on('end', function(){ | |
post_data.push(new Buffer(file_contents, 'utf8')) | |
post_data.push(new Buffer("\r\n--" + boundary + "--"), 'ascii'); | |
MakePost(post_data, boundary); | |
}); | |
} | |
function MakePost(post_data, boundary) { | |
var length = 0; | |
for(var i = 0; i < post_data.length; i++) { | |
length += post_data[i].length; | |
} | |
var post_options = { | |
host: '127.0.0.1', | |
port: '80', | |
path: '/labs/yuanhuang/test.php', | |
method: 'POST', | |
headers : { | |
'Content-Type' : 'multipart/form-data; boundary=' + boundary, | |
'Content-Length' : length | |
} | |
}; | |
var post_request = http.request(post_options, function(response){ | |
response.setEncoding('utf8'); | |
response.on('data', function(chunk){ | |
console.log(chunk); | |
}); | |
}); | |
for (var i = 0; i < post_data.length; i++) { | |
post_request.write(post_data[i]); | |
} | |
post_request.end(); | |
} | |
PreparePost(); | |
/* test.php */ | |
/* | |
<?php | |
print_r($_POST); | |
print_r($_FILES); | |
?> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment