1、实现一个文件上传展示

创建目录如下:
image.png

编写index.js代码:

  1. var server = require("./server");
  2. var router = require("./router");
  3. var requestHandlers = require('./requestHandlers')
  4. var handle = {}
  5. handle["/"] = requestHandlers.start;
  6. handle["/start"] = requestHandlers.start;
  7. handle["/upload"] = requestHandlers.upload;
  8. handle["/show"]= requestHandlers.show;
  9. server.start(router.route, handle);

编写requestHandlers.js代码:

  1. var fs = require("fs");
  2. var path = require("path")
  3. var formidable = require("formidable");
  4. const url = path.join(process.cwd(), '/tmp/test.png')
  5. function start(response) {
  6. var body = '<html>' +
  7. '<head>' +
  8. '<meta http-equiv="Content-Type" ' +
  9. 'content="text/html; charset=UTF-8" />' +
  10. '</head>' +
  11. '<body>' +
  12. '<form action="/upload" enctype="multipart/form-data" ' +
  13. 'method="post">' +
  14. '<input type="file" name="upload">' +
  15. '<input type="submit" value="Upload file" />' +
  16. '</form>' +
  17. '</body>' +
  18. '</html>';
  19. response.writeHead(200, { "Content-Type": "text/html" });
  20. response.write(body);
  21. response.end();
  22. }
  23. function upload(response, request) {
  24. var form = new formidable.IncomingForm();
  25. form.parse(request, function (error, fields, files) {
  26. fs.renameSync(files.upload.filepath, url);
  27. response.writeHead(200, { "Content-Type": "text/html" });
  28. response.write("received image:<br/>");
  29. response.write("<img src='/show' />");
  30. response.end();
  31. });
  32. }
  33. function show(response) {
  34. fs.readFile(url, "binary", function (error, file) {
  35. if (error) {
  36. response.writeHead(500, { "Content-Type": "text/plain" });
  37. response.write(error + "\n");
  38. response.end();
  39. } else {
  40. response.writeHead(200, { "Content-Type": "image/png" });
  41. response.write(file, "binary");
  42. response.end();
  43. }
  44. });
  45. }
  46. exports.start = start;
  47. exports.upload = upload;
  48. exports.show = show;

编写router.js代码:

  1. function route(handle, pathname, response, request) {
  2. if (typeof handle[pathname] === 'function') {
  3. return handle[pathname](response, request);
  4. } else {
  5. response.writeHead(404, { "Content-Type": "text/plain" });
  6. response.write("404 Not found");
  7. response.end();
  8. }
  9. }
  10. exports.route = route;

编写server.js代码:

  1. var http = require("http");
  2. var url = require("url");
  3. function start(route, handle) {
  4. function onRequest(request, response) {
  5. var pathname = url.parse(request.url).pathname;
  6. route(handle, pathname, response, request);
  7. }
  8. http.createServer(onRequest).listen(8888, () => {
  9. console.log("Server has started 8888.");
  10. });
  11. }
  12. exports.start = start;

运行效果:
image.png
image.png