NODEJS 上传文件

index.js 文件实现路由以及功能实现。


var http = require("http");
var url = require("url");
var querystring = require("querystring");
var port = 8888;
function start(route, handle) {
	function onRequest(request, response) {
		var postData = "";
		var pathname = url.parse(request.url).pathname;
		console.log("Request:" + pathname + " received.");
		var ret = route(request, handle, pathname, response);
	}
	http.createServer(onRequest).listen(port);
	console.log("Server has started.");
}

function route(request, handle, pathname, response) {
	console.log("About to route a request for " + pathname);
	if (typeof handle[pathname] === 'function') {
		handle[pathname](request, response);
	} else {
		console.log("No request handler found for " + pathname);
		response.writeHead(404, {
			"Content-Type" : "text/plain"
		});
		response.write("404 Not found");
		response.end();
	}
}
function start_handler(request, response) {
	console.log("No request handler found for ");
	var body = '' +
	'' + 
	'' + 
	'' + '' + 
	'
' + '' + '' + '
' + '' + ''; response.writeHead(200, { "Content-Type" : "text/html" }); response.write(body); response.end(); } function upload_handler(request, response) { console.log("Request handler 'upload' was called."); var fs = require("fs"); var formidable = require("formidable"); var form = new formidable.IncomingForm(); form.uploadDir = "tmp"; console.log("about to parse"); form.parse(request, function (error, fields, files) { console.log("parsing done"); console.log(files.upload); console.log(files.upload.path); fs.renameSync(files.upload.path, "tmp/test"); //文件操作rename操作必须是同一个逻辑分区。否则会Rename失败 response.writeHead(200, { "Content-Type" : "text/html" }); response.write("received image:
"); response.write(""); res.end(sys.inspect({ fields : fields, files : files })); response.end(); }); } function show_handler(request, response) { console.log("Request handler 'show' was called."); var fs = require("fs"); fs.readFile("tmp/test", "binary", function (error, file) { if (error) { response.writeHead(500, { "Content-Type" : "text/plain" }); response.write(error + "\n"); response.end(); } else { response.writeHead(200, { "Content-Type" : "image" }); response.write(file, "binary"); response.end(); } }); } exports.start = start; exports.route = route; exports.start_handler = start_handler; exports.upload_handler = upload_handler; exports.show_handler = show_handler;


app.js 创建Server实例。

var server = require("./start");
//var router = require("./router");

//server.start(server.route);
//var requestHandlers = require("./start");

var handle = {}
handle["/"] = server.start_handler;
handle["/start"] = server.start_handler;
handle["/upload"] = server.upload_handler;
handle["/show"] = server.show_handler;

server.start(server.route, handle);



你可能感兴趣的:(杂乱)