NodeJS使用formidable實現檔案上傳

來源:互聯網
上載者:User

標籤:router   for   clist   lock   text   back   color   r.js   view   

  最近自學了一下NodeJS,然後做了一個小demo,實現歌曲的添加、修改、播放和刪除的功能,其中自然要實現音樂和圖片的上傳功能。於是上網尋找資料,找到了一個formidable外掛程式,該外掛程式可以很好的實現檔案的上傳功能。該小demo用到了MySQL資料庫,所有的資料都存放到了資料庫中。下面簡單說一些如何使用。

1.建立app.js主檔案
const express = require(‘express‘);const router = require(‘./router‘);const path = require(‘path‘);const bodyParser = require(‘body-parser‘);const app = express();//靜態資源服務app.use(‘/uploads‘, express.static(path.join(__dirname, ‘uploads‘)));app.use(‘/node_modules‘, express.static(path.join(__dirname, ‘node_modules‘)));//配置模板引擎app.set(‘views‘, path.join(__dirname, ‘views‘));app.engine(‘.html‘, require(‘ejs‘).renderFile);app.set(‘view engine‘, ‘html‘);//配置解析普通表單post請求體app.use(bodyParser.urlencoded({extended:false}));//載入路由系統app.use(router);app.listen(3000, ‘127.0.0.1‘, () => {    console.log(‘server is running at port 3000.‘);})
2.html檔案中的form表單

add.html檔案:

<form action="/add" method="post" enctype="multipart/form-data">       <div class="form-group">        <label for="title">標題</label>        <input type="text" class="form-control" id="title" name="title" placeholder="請輸入音樂標題">      </div>      <div class="form-group">        <label for="artist">歌手</label>        <input type="text" class="form-control" id="singer" name="singer" placeholder="請輸入歌手名稱">      </div>      <div class="form-group">        <label for="music_file">音樂</label>        <input type="file" id="music" name="music" accept="audio/*">        <p class="help-block">請選擇要上傳的音樂檔案.</p>      </div>      <div class="form-group">        <label for="image_file">海報</label>        <input type="file" id="poster" name="img" accept="image/*">        <p class="help-block">請選擇要上傳的音樂海報.</p>      </div>      <button type="submit" class="btn btn-success">點擊添加</button>    </form>

注意:method="post" enctype="multipart/form-data"

3.建立路由router.js檔案
const express = require(‘express‘);const router = express.Router();const handler = require(‘./handler‘);router    .get(‘/‘, handler.showIndex)    .get(‘/musicList‘, handler.getMusicList)    .get(‘/add‘, handler.showAdd)    .post(‘/add‘, handler.doAdd)    .get(‘/edit‘, handler.showEdit)    .post(‘/edit‘, handler.doEdit)    .get(‘/remove‘, handler.doRemove)module.exports = router;

  注意:router.js檔案中的依賴不用多說。

4.建立handler.js檔案
const formidable = require(‘formidable‘);
const config = require(‘./config‘);
const db = require(‘./common/db‘);
const path = require(‘path‘);
const fs = require(‘fs‘);
exports.doAdd = (req, res) => {    const form = new formidable.IncomingForm();    form.uploadDir = config.uploadDir;//上傳檔案的儲存路徑    form.keepExtensions = true;//儲存副檔名    form.maxFieldsSize = 20 * 1024 * 1024;//上傳檔案的最大大小    form.parse(req, (err, fields, files) => {        if (err) {            throw err;        }        const title = fields.title;        const singer = fields.singer;        const music = path.basename(files.music.path);        const img = path.basename(files.img.path);        db.query(‘INSERT INTO music (title,singer,music,img) VALUES (?,?,?,?)‘, [            title,            singer,            music,            img        ], (err, rows) => {            if (err) {                throw err;            }            res.redirect(‘/‘);        })    })};

 

NodeJS使用formidable實現檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.