Node.js實現文件上傳功能
作者:zhanhailiang 日期:2014-11-16
本文將介紹如何使用Node.js實現文件上傳功能。
1. 初始化項目信息:npm init
[root@~/wade/nodejs/nodejs-upload-image-demo]# npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sane defaults.See
npm help json
for definitive documentation on these fields and exactly what they do.Use
npm install <pkg> --save
afterwards to install a package and save it as a dependency in the package.json file.Press ^C at any time to quit. name: (nodejs-upload-image-demo) version: (1.0.0) description: how to use node.js to upload an image entry point: (index.js) test command: git repository: (https://github.com/billfeller/nodejs-upload-image-demo.git) keywords: author: billfeller license: (ISC) MIT About to write to /root/wade/nodejs/nodejs-upload-image-demo/package.json:
{ "name": "nodejs-upload-image-demo", "version": "1.0.0", "description": "how to use node.js to upload an image", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "
Is this ok? (yes) yes</pre>
2. 修改package.json,配置啟動命令:
"scripts": { "start": "node index.js" },3. 安裝依賴模塊:npm install formidable –save
4. 功能實現:
-
index.js——統一入口,包括請求處理器注冊;</li>
-
server.js——服務器模塊,包括服務器創建,監聽請求,執行路由策略;</li>
-
router.js——路由策略,根據請求url路由到相應的處理器進行請求處理;</li>
-
requestHandler.js——請求處理器;</li> </ul>
完整源碼請見:https://github.com/billfeller/nodejs-upload-image-demo
5. 啟動服務器:
[root@~/wade/nodejs/nodejs-upload-image-demo]# npm start
> nodejs-upload-image-demo@1.0.0 start /root/wade/nodejs/nodejs-upload-image-demo > node index.js
server is starting</pre>
6. 通過瀏覽器訪問并上傳圖片:
6. 參考:
- </li>
- </li> </ul> </div> </div> 來自:http://blog.csdn.net/billfeller/article/details/41162179