Node js test http upload (multipart/form-data)
var http = require("http"); var url = require("url"); var fs = require("fs"); // fs.readFile("D:\\02_bat\\Explorer.7z", function(err, data) { // console.log(data); // }); var server = http.createServer(function(req, res) { //req.setEncoding("binary"); var chunk; var j = 0; req.on("data", function(data) { //console.log(data + ""); var buf = new Buffer(data, "binary"); var boundary = getBoundary(req); var startStr = "Content-Type: application/octet-stream\r\n"; var start = getIndexInBuffer(startStr, buf) + 1; var endStr = "--" + boundary + "--"; //"---------------------------acebdf13572468--"; var end = getIndexInBuffer(endStr, buf) - endStr.length; var file = buf.slice(start, end); fs.writeFile("aa.7z", file); }); res.end(req.url); }); // Server would listen on port server.listen(8889); ////////////////////////////////////// function getBoundary(req) { //Content-Type: multipart/form-data; boundary=${bound} var content_type = req.headers["content-type"]; var arr = content_type.split(‘;‘); for (var i in arr) { var str = "boundary="; var index = arr[i].indexOf(str); if (index > -1) { return arr[i].substring(index + str.length); } } } function getIndexInBuffer(str, buf) { var buf2 = new Buffer(str); for (var i = 0; i < buf.length; i++) { if (buf[i] === buf2[0]) { var b = true; for (var j = 1; j < buf2.length; j++) { i++; if (buf[i] === buf2[j]) { b = true; } else { b = false; break; } } if (b) { return i; } } } return -1; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。