---
title: "nodejs上传样例学习"
author: "oboaix"
date: "2014-10-08T14:01:12Z"
tags: []
categories: ["开源软件"]
slug: "nodejs"
draft: false
lastmod: "2014-10-08T14:01:12Z"
id: 2125276
url: "https://xiaobo.iteye.com/blog/2125276"
---

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台，用来方便地搭建快速的易于扩展的网络应用· Node.js 借助事件驱动，非阻塞I/O 模型变得轻量和高效，非常适合运行在分布式设备的数据密集型的实时应用

 

简单的说 Node.js 就是运行在服务端的 JavaScript。

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。

Node.js是一个事件驱动I/O服务端JavaScript环境，基于Google的V8引擎，V8引擎执行Javascript的速度非常快，性能非常好。

 

Node.js是一个可以快速构建网络服务及应用的平台。该平台的构建是基于Chrome's JavaScript runtime，也就是说，实际上它是对Google V8引擎（应用于Google Chrome浏览器)进行了封装。

V8引擎执行Javascript的速度非常快，性能非常好。Node对一些特殊用例进行了优化，提供了替代的API，使得V8在非浏览器环境下运行得更好。

例如，在服务器环境中，处理二进制数据通常是必不可少的，但Javascript对此支持不足，因此，V8.Node增加了Buffer类，方便并且高效地处理二进制数据。因此，Node不仅仅简单地使用了V8，还对其进行了优化，使其在各环境下更加给力。

 

优点：

RESTful API

单线程

Node.js可以在不新增额外线程的情况下，依然可以对任务进行并行处理—— Node.js是单线程的。它通过事件轮询（event loop）来实现并行操作，对此，我们应该要充分利用这一点——尽可能的避免阻塞操作，取而代之，多使用非阻塞操作。

非阻塞IO

V8虚拟机

事件驱动

 

 

该样例使用的版本为：

v0.10.32

 

使用命令检查：

node –version

 

 

实验一个使用nodejs上传的示例，参考文档：

[http://nodejs.org/](http://nodejs.org/)

[http://nodejs.org/api/fs.html](http://nodejs.org/api/fs.html)

[http://www.w3cschool.cc/nodejs/nodejs-tutorial.html](http://www.w3cschool.cc/nodejs/nodejs-tutorial.html)

 

要使用上传功能，需要安装*formidable*模块。Node.js有它自己的包管理器，叫*NPM*。它可以让安装Node.js的外部模块变得非常方便，通过如下一条命令就可以完成该模块的安装：

 

npm install formidable

 

用require语句将其引入即可：

 

var formidable = require("formidable");

 

另外这里有个小小的说明：

NodeJS”热部署“代码，实现动态调试，实现类似tomcat或websphere等一些主流的web应用服务器那样保存即热部署。

避免过多的使用命令：

control + C

node server.js

 

使用方法很简单，首先使用 npm 安装 supervisor：

 

$ npm install -g supervisor

 

接下来，使用 supervisor 命令启动 index.js：

 

$ supervisor index.js

 

可以看看测试效果，当你修改相应的js页面代码后。

 

第一个js代码，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);//调用模块方法

 

第二个js, 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;

    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response, request);

  }

 

  http.createServer(onRequest).listen(9920,'localhost');//启动本地服务应用，端口为9920

  console.log("Server has started.");

}

 

exports.start = start;

 

 

第三个js代码，路由功能，router.js内容如下：

 

**function** route(handle, pathname, response, 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;

 

第四个js代码, 实际业务处理功能代码, requestHandlers.js代码如下：

 

**var** querystring = require("querystring"),

    fs = require("fs"),

    formidable = require("formidable");

 

**var** file\_path="R:\\\\temp\\\\NODE.jpg";//虚拟图片路径

 

**function** start(response) {

  console.log("Request handler 'start' was called.");

 

  **var** body = '&lt;html&gt;'+

    '&lt;head&gt;'+

    '&lt;meta http-equiv="Content-Type" content="text/html; '+

    'charset=UTF-8" /&gt;'+

    '&lt;/head&gt;'+

    '&lt;body&gt;'+

    '&lt;form action="/upload" enctype="multipart/form-data" '+

    'method="post"&gt;'+

    '&lt;input type="text" style="width: 160px;"  id="f\_file" readonly="readonly" value=""&gt;&lt;input type="button" value="Browse..." onClick="document.getElementById(\\'t\_file\\').click()"&gt;'+

    '&lt;input name="upload" type="file" id="t\_file" onchange="document.getElementById(\\'f\_file\\').value=this.value" style="display:none"&gt;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+

    '&lt;input type="submit" value="Upload File" onclick="var a = document.getElementById(\\'f\_file\\').value; if (a ==\\'\\'){alert(\\'Please select image file...\\'); return false;}"/&gt;'+

   

    '&lt;/form&gt;'+

    '&lt;/body&gt;'+

    '&lt;/html&gt;';

 

    response.writeHead(200, {"Content-Type": "text/html"});

    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.uploadDir = "R:/tmp"; //记得一定得设置一个临时存放图片的路径位置

  form.parse(request, **function**(error, fields, files) {

    console.log("parsing done");

    fs.renameSync(files.upload.path,file\_path);

    response.writeHead(200, {"Content-Type": "text/html"});

    response.write("received image:&lt;br/&gt;");

    response.write("&lt;img src='/show' /&gt;");

    response.end();

  });

}

 

**function** show(response) {

  console.log("Request handler 'show' was called.");

  fs.readFile(file\_path, "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/jpg"});//图片格式

      response.write(file, "binary");

      response.end();

    }

  });

  console.log("Request handler 'show' was called over.");

}

 

exports.start = start;

exports.upload = upload;

exports.show = show;

 

 

操作步骤：

1, 进入到js目录路径下面

   
![](http://dl2.iteye.com/upload/attachment/0101/7445/970d3598-0dee-3c50-9e8c-fec03125703d.jpg)  
 

 

2, 使用node index.js 或者 supervisor index.js启动服务

   
![](http://dl2.iteye.com/upload/attachment/0101/7447/06170805-8e70-32e4-b717-1866ce47d5de.jpg)  
 

 

3, 进入到浏览器

   
![](http://dl2.iteye.com/upload/attachment/0101/7449/79a60be1-ef24-36a2-85b3-0c9b1a7544b0.jpg)  
 

 

4, 选择图片上传

   
![](http://dl2.iteye.com/upload/attachment/0101/7451/2219faac-aab5-3d7c-a76d-e29d4c9740ee.jpg)  
 

 

5, 点击Upload File按钮之后展示上次之后的效果图片如下：

 

   
![](http://dl2.iteye.com/upload/attachment/0101/7453/01214e91-d41d-3c30-aeb0-ea105de448dc.jpg)