Node.js新手教程——怎樣實現檔案上傳功能

來源:互聯網
上載者:User

標籤:

  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入門
  • nodebeginner

Node.js新手教程——怎樣實現檔案上傳功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.