nodejs 模拟form表单

公用方法:

function postFile(fileKeyValue, req) {
	var boundaryKey = Math.random().toString(16);
	var enddata = '\r\n----' + boundaryKey + '--';

	var files = new Array();
	for (var i = 0; i < fileKeyValue.length; i++) {
		var content = "\r\n----" + boundaryKey + "\r\n"
				+ "Content-Type: application/octet-stream\r\n"
				+ "Content-Disposition: form-data; name=\""
				+ fileKeyValue[i].urlKey + "\"; filename=\""
				+ path.basename(fileKeyValue[i].urlValue) + "\"\r\n"
				+ "Content-Transfer-Encoding: binary\r\n\r\n";
		var contentBinary = new Buffer(content, 'utf-8');// 当编码为ascii时,中文会乱码。
		files.push({
			contentBinary : contentBinary,
			filePath : fileKeyValue[i].urlValue
		});
	}
	var contentLength = 0;
	for (var i = 0; i < files.length; i++) {
		var stat = fs.statSync(files[i].filePath);
		contentLength += files[i].contentBinary.length;
		contentLength += stat.size;
	}

	req.setHeader('Content-Type', 'multipart/form-data; boundary=--'
			+ boundaryKey);
	req.setHeader('Content-Length', contentLength + Buffer.byteLength(enddata));

	// 将参数发出
	var fileindex = 0;
	var doOneFile = function() {
		req.write(files[fileindex].contentBinary);
		var fileStream = fs.createReadStream(files[fileindex].filePath, {
			bufferSize : 4 * 1024
		});
		fileStream.pipe(req, {
			end : false
		});
		
		
		fileStream.on('end', function() {
			fileindex++;
			if (fileindex == files.length) {
				req.end(enddata);
			} else {
				doOneFile();
			}
		});
	};
	if (fileindex == files.length) {
		req.end(enddata);
	} else {
		doOneFile();
	}
}

调用:

app.get('/anthor/wokaotest', function(req, res, next) {
		var files = [ {
			urlKey : "file1",
			urlValue : "E:\\qumao.png"
		}, {
			urlKey : "file2",
			urlValue : "E:\\1.jpg"
		}]
		var options = {
			host : "localhost",
			port : "2300",
			method : "POST",
			path : "/anthor/wokaotest_post"
		}


		var req = http.request(options, function(res) {
			console.log("RES:" + res);
			console.log('STATUS: ' + res.statusCode);
			console.log('HEADERS: ' + JSON.stringify(res.headers));
			// res.setEncoding("utf8");
			res.on("data", function(chunk) {
				console.log("BODY:" + chunk);
			})
		})


		req.on('error', function(e) {
			console.log('problem with request:' + e.message);
			console.log(e);
		})
		postFile(files, req);
		console.log("done");


		            
		            
// var uptoken = new
// qiniu.rs.Client().stat("mycustom","Lighthouse.jpg",function(err,result,res){
// //console.log(err);
// console.log(res.fsize);
// //console.log(res);
// });
		
	});


应用:

	app.post('/anthor/wokaotest_post', function(req, res, next) {
		console.log("你成功了。。。。。");
		res.end("你说的对");
	});
	app.post(packageName + '/file/upload', function(request, response, next) {
		var boundaryKey = "WebKitFormBoundaryPp7hAwEB15BvF0W0";//Math.random().toString(16);
		var fileKeyValue =  {
			urlKey : "file1",
			urlValue : "E:\\qumao.png"
		}
		var fileValue = [
             {
            	 name:"key",
            	 value:"mytest333",
             }, {
            	 name:"x:phototogo",
            	 value:"phototogo",
             }];
		
		var options = {
				host : "localhost",
				port : "2300",
				method : "POST",
				path : "/anthor/wokaotest_post"
			}
			
		var req = http.request(options, function(res) {
			res.on("data", function(chunk) {
				console.log(chunk.toString("utf-8",0,chunk.length));
				response.end(JSON.stringify({'err':'','msg':{'url':'htpp://www.baidu.com','localname':'localhost','id':'1'}}));
			})
		})

		req.on('error', function(e) {
			console.log('problem with request:' + e.message);
			console.log(e);
		})

		

		var files = new Array();
		var content = "\r\n----" + boundaryKey + "\r\n"
				+ "Content-Type: application/octet-stream\r\n"
				+ "Content-Disposition: form-data; name=\"file\"; filename=\"yq_j.png\"\r\n"
				+ "Content-Type: image/png \r\n\r\n";
		
		var content2 = "\r\n----" + boundaryKey + "\r\n"
			+ "Content-Type: application/octet-stream\r\n"
			+ "Content-Disposition: form-data; name=\""
			+ fileKeyValue.urlKey + "\"; filename=\""
			+ path.basename(fileKeyValue.urlValue) + "\"\r\n"
			+ "Content-Type: image/png\r\n\r\n";
		
		
		var contentLength = 0;
		
		
		var fileValueContent = [];
		for(var i =0;i<fileValue.length;i++){
			var _file = fileValue[i];
			var _filekey = "\r\n----" + boundaryKey + "\r\n"
			+ "Content-Disposition: form-data; name=\""+_file.name+"\" \r\n\r\n"
			+ _file.value+"\r\n";
			var _fileBinary = new Buffer(_filekey, 'utf-8');
			fileValueContent.push(_fileBinary);
			contentLength += _fileBinary.length;
		}
		
		
		var tokenMyTest = "\r\n----" + boundaryKey + "\r\n"
		+ "Content-Disposition: form-data; name=\"token\" \r\n\r\n"
		+"vHCxlVbENwofJS6LKQXwm:coCCwsMATDlyMJSCGtB8=:eyJzY29wZSIDU4MTQzNDd9";
		contentLength += new Buffer(tokenMyTest, 'utf-8').length;
		
		var contentBinary = new Buffer(content, 'utf-8');// 当编码为ascii时,中文会乱码。
		files.push({
			contentBinary : contentBinary,
			filePath : fileKeyValue.urlValue
		});
		
		contentLength += files[0].contentBinary.length;

		
		
		/****/
		 var chunks = [];
		 var size = 0;
		 request.addListener("data", function(data) { // 有新的数据包到达就执行
			 chunks.push(data);
			 size += data.length;
		 });
		 request.addListener("end", function() { // 数据传输完毕
			var buf = Buffer.concat(chunks, size);
			contentLength += buf.length;

			
			var enddata = '\r\n----' + boundaryKey + '--';
			contentLength += Buffer.byteLength(enddata);
			req.setHeader('Content-Type', 'multipart/form-data; boundary=--'+ boundaryKey);
			req.setHeader('Content-Length', contentLength );
			
//			req.setHeader('Origin', "https://portal.qiniu.com" );
//			req.setHeader('Referer', "https://portal.qiniu.com/bucket/resource?bucket=mycustom" );
			
			for(var i =0;i<fileValueContent.length;i++){
				req.write(fileValueContent[i]);
			}
			req.write(tokenMyTest);
			
			// 将参数发出
			req.write(files[0].contentBinary);
			req.write(buf);
			req.end(enddata);
		});
		
		
		/**
		var chunks = [];
		 var size = 0;
		fileStream.on('data',function(data){
			
			chunks.push(data);
			size += data.length;
		});

		fileStream.on('end', function() {
			var buf = Buffer.concat(chunks, size);
			console.log(buf);
			req.write(buf);
			req.end(enddata);
		});**/
		

	});





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值