• 一个node.js图片上传显示小应用


    文件结构如下:

    实现的功能有:

    • 可以通过浏览器使用。
    • 当请求http://domain/start时,可以看到一个欢迎页面,页面上有一个文件上传的表单。
    • 用户可以选择一个图片并提交表单,随后文件将被上传到http://domain/upload,该页面完成上传后会把图片显示在页面上。

    模块的功能:

    • HTTP服务器:提供Web页面 server.js
    //请求(require)Node.js自带的 http 模块,并且把它赋值给 http 变量
    var http = require("http");
    var url = require("url");
    
    function start(route, handle) {
      //将路由函数作为参数传递
      function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        //找出浏览器请求的URL路径
        console.log("Request for " + pathname + " received.");
        //在 onRequest (我们的回调函数)触发的地方,用 console.log 输出了一段文本
        route(handle, pathname, response, request);
        
      }
    
      http.createServer(onRequest).listen(8888);
      //调用http模块提供的函数: createServer 
      //这个函数会返回一个对象,这个对象有一个叫做 listen 的方法,
      //这个方法有一个数值参数,指定这个HTTP服务器监听的端口号
      console.log("Server has started.");
      //在HTTP服务器开始工作之后,也输出一段文本
    }
    
    exports.start = start;
    其中找出浏览器请求的URL路径:

    • 对于不同的请求,根据请求的URL,我们的服务器需要给予不同的响应,因此我们需要一个路由,用于把请求对应到请求处理程序(request handler) router.js
    //编写路由
    //将response对象(从服务器的回调函数onRequest()获取)
    //通过请求路由传递给请求处理程序。 随后,处理程序就可以采用该对象上的函数来对请求作出响应
    function route(handle, pathname, response, request) {
        //传递request对象
      console.log("About to route a request for " + pathname);
      if (typeof handle[pathname] === 'function') {
        handle[pathname](response, request);
        //首先检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数
      } else {
        console.log("No request handler found for " + pathname);
        response.writeHead(404, {"Content-Type": "text/html"});
        response.write("404 Not found");
        response.end();
      }
    }
    
    exports.route = route;
    • 请求处理程序(request handler) requestHandler.js
    var querystring = require("querystring"),
    //只把POST数据中我们感兴趣的部分传递给请求路由和请求处理程序
        fs = require("fs"),
        //将文件读取到我们的服务器中,使用一个叫fs的模块
        formidable = require("formidable");
    //需要运行 npm install formidable下载该模块
    //该模块做的就是将通过HTTP POST请求提交的表单,在Node.js中可以被解析。 //我们要做的就是创建一个新的IncomingForm,它是对提交表单的抽象表示, //之后,就可以用它解析request对象,获取表单中需要的数据字段 function start(response) { console.log("Request handler 'start' was called."); var body = '<html>'+ '<head>'+ '<meta http-equiv="Content-Type" content="text/html; '+ 'charset=UTF-8" />'+ '</head>'+ '<body>'+ //在/start表单中添加一个文件上传元素 '<form action="/upload" enctype="multipart/form-data" '+ 'method="post">'+ '<input type="file" name="upload" multiple="multiple">'+ '<input type="submit" value="Upload file" />'+ '</form>'+ '</body>'+ '</html>'; response.writeHead(200, {"Content-Type": "text/html"}); //当收到请求时,使用 response.writeHead() 函数发送一个HTTP状态200和HTTP头的内容类型(content-type) response.write(body); response.end(); } function upload(response, request) { console.log("Request handler 'upload' was called."); var form = new formidable.IncomingForm(); console.log("about to parse"); form.parse(request, function(error, fields, files) { console.log("parsing done"); fs.renameSync(files.upload.path, "/tmp/test.png"); //确保该文件保存成/tmp/test.png response.writeHead(200, {"Content-Type": "text/html"}); response.write("received image:<br/>"); response.write("<img src='/show' />"); //将上传的图片内嵌到/uploadURL输出的HTML中 response.end(); }); } function show(response) { //添加/showURL的请求处理程序,该处理程序直接硬编码将文件/tmp/test.png内容展示到浏览器中 console.log("Request handler 'show' was called."); fs.readFile("/tmp/test.png", "binary", function(error, file) { // if(error) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(error + " "); 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;
    • 入口 index.js
    var server = require("./server");
    var router = require("./router");
    var requestHandlers = require("./requestHandlers");
    //创建一个叫做requestHandlers的模块,请求处理函数
    
    var handle = {}
    handle["/"] = requestHandlers.start;
    //在对象中添加一个键为"/"的属性,对应requestHandlers.start
    //即可将不同的URL映射到相同的请求处理程序上
    handle["/start"] = requestHandlers.start;
    handle["/upload"] = requestHandlers.upload;
    handle["/show"] = requestHandlers.show;
    
    //路由函数可以被注入到服务器中
    server.start(router.route, handle);

    在命令行中运行 node index.js

    效果:

    点击选择文件 Upload file:

    图片已经上传到服务端:

     参考:http://www.nodebeginner.org/index-zh-cn.html

  • 相关阅读:
    查看ASM 使用率
    修改一行和修改全表的TX锁
    OCP-1Z0-053-V12.02-683题
    专栏成书亦可行也!——leo鉴书48
    Java用正则表达式判断是否为IP
    OCP-1Z0-053-V12.02-594题
    OCP-1Z0-053-V12.02-585题
    OCP-1Z0-053-V12.02-569题
    OCP-1Z0-053-V12.02-568题
    OCP-1Z0-053-V13.02-517题
  • 原文地址:https://www.cnblogs.com/rlann/p/6285661.html
Copyright © 2020-2023  润新知