1、实现一个文件上传展示
创建目录如下:
编写index.js代码:
var server = require("./server");
var router = require("./router");
var requestHandlers = require('./requestHandlers')
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"]= requestHandlers.show;
server.start(router.route, handle);
编写requestHandlers.js代码:
var fs = require("fs");
var path = require("path")
var formidable = require("formidable");
const url = path.join(process.cwd(), '/tmp/test.png')
function start(response) {
var body = '<html>' +
'<head>' +
'<meta http-equiv="Content-Type" ' +
'content="text/html; charset=UTF-8" />' +
'</head>' +
'<body>' +
'<form action="/upload" enctype="multipart/form-data" ' +
'method="post">' +
'<input type="file" name="upload">' +
'<input type="submit" value="Upload file" />' +
'</form>' +
'</body>' +
'</html>';
response.writeHead(200, { "Content-Type": "text/html" });
response.write(body);
response.end();
}
function upload(response, request) {
var form = new formidable.IncomingForm();
form.parse(request, function (error, fields, files) {
fs.renameSync(files.upload.filepath, url);
response.writeHead(200, { "Content-Type": "text/html" });
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
function show(response) {
fs.readFile(url, "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/png" });
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
编写router.js代码:
function route(handle, pathname, response, request) {
if (typeof handle[pathname] === 'function') {
return handle[pathname](response, request);
} else {
response.writeHead(404, { "Content-Type": "text/plain" });
response.write("404 Not found");
response.end();
}
}
exports.route = route;
编写server.js代码:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888, () => {
console.log("Server has started 8888.");
});
}
exports.start = start;
运行效果: