標籤:
zhanhailiang 日期:2014-11-16
本文將介紹怎樣使用Node.js實現檔案上傳功能。
1. 初始化項目資訊:npm init
[root@~/wade/nodejs/nodejs-upload-image-demo]# npm initThis 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 fieldsand exactly what they do. Use `npm install <pkg> --save` afterwards to install a package andsave 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 imageentry point: (index.js) test command: git repository: (https://github.com/billfeller/nodejs-upload-image-demo.git) keywords: author: billfellerlicense: (ISC) MITAbout 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": "https://github.com/billfeller/nodejs-upload-image-demo.git" }, "author": "billfeller", "license": "MIT", "bugs": { "url": "https://github.com/billfeller/nodejs-upload-image-demo/issues" }, "homepage": "https://github.com/billfeller/nodejs-upload-image-demo"} Is this ok? (yes) yes
2. 改動package.json,配置啟動命令:
"scripts": { "start": "node index.js" },
3. 安裝相依模組:npm install formidable –save
4. 功能實現:
- index.js——統一入口,包含要求處理常式注冊;
- server.js——server模組,包含server建立,監聽請求,運行路由策略;
- router.js——路由策略,依據請求url路由到對應的處理器進行請求處理;
- requestHandler.js——要求處理常式;
完整原始碼請見:https://github.com/billfeller/nodejs-upload-image-demo
5. 啟動server:
[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
6. 通過瀏覽器訪問並上傳圖片:
6. 參考:
Node.js新手教程——怎樣實現檔案上傳功能