標籤:des style blog http io color ar os 使用
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——伺服器模組,包括伺服器建立,監聽請求,執行路由策略;
- router.js——路由策略,根據請求url路由到相應的處理器進行請求處理;
- requestHandler.js——要求處理常式;
完整源碼請見: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
6. 通過瀏覽器訪問並上傳圖片:
6. 參考:
Node.js入門教程——如何?檔案上傳功能