Express教程04:處理文件上傳

閱讀更多系列文章請訪問個人GitHub博客,示例代碼請訪問這裏

使用multer處理文件上傳

處理文件上傳,天然也離不開中間件的幫助,此處以Multer爲例介紹一下文件上傳中間件的使用。html

但Multer只能處理enctype="multipart/form-data"的form表單提交的數據。git

示例代碼:/lesson04/server.jsgithub

  1. 安裝Multer:npm install --save multerexpress

  2. 引入Multer:npm

    const multer = require('multer')
    複製代碼
  3. 設置保存上傳文件路徑:json

    const upload = multer({
      dest: './static/upload'
    })
    複製代碼
  4. 處理上傳文件:bash

    server.use(upload.any())
    複製代碼
  5. 接收文件上傳結果:服務器

    server.post('/upload', (req, res, next) => {
      console.log(req.files)
    })
    複製代碼

啓動服務器後,訪問http://localhost:8080/index.html,上傳一個文件,就能夠看到控制檯打印的結果:app

[ { fieldname: 'file',
    originalname: '091557_Dp1c_3669181.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: './static/upload',
    filename: '8952900376066f666af68c019ad85993',
    path: 'static\\upload\\8952900376066f666af68c019ad85993',
    size: 136586 } ]
複製代碼

同時能夠看到在/lesson04/static/upload文件夾中,有一個名爲8952900376066f666af68c019ad85993的文件,即爲上傳的文件。less

使用body-parser補充處理數據

Multer的不足之處是沒法處理普通表單提交的數據,以及經過Fetch提交的數據,因此須要配合body-parser使用,完整代碼以下:

示例代碼:/lesson04/server.js

const express = require('express')
const bodyParser = require('body-parser')

const server = express()

server.listen(8080)

// 引入Multer
const multer = require('multer')

// 設置保存上傳文件路徑
const upload = multer({
  dest: './static/upload'
})

// 處理上傳文件
server.use(upload.any())

// 處理表單提交,對應請求頭application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({
  extended: false // 爲true時將使用qs庫處理數據,一般不須要
}))

// 處理fetch請求,對應請求頭application/json
server.use(bodyParser.json())

// 接收文件上傳結果
server.post('/upload', (req, res, next) => {
  console.log(req.body)
  console.log(req.files)
  res.send({
    error: 0,
    data: req.body,
    msg: '上傳成功'
  })
})

server.get('/reg', (req, res, next) => {
  console.log(req.query)
  res.send({
    error: 0,
    data: req.query,
    msg: '註冊成功'
  })
})


server.post('/login', (req, res, next) => {
  console.log(req.body)
  res.send({
    error: 0,
    data: req.body,
    msg: '登錄成功'
  })
})

server.use(express.static('./static/'))

console.log(`Server started at 8080`)
複製代碼

此時填寫表單並上傳文件,控制檯打印的結果爲:

[Object: null prototype] { username: 'test', password: 'test' }
[ { fieldname: 'file',
    originalname: '091557_Dp1c_3669181.png',
    encoding: '7bit',
    mimetype: 'image/png',
    destination: './static/upload',
    filename: '266005473a95b69207dd145241439db0',
    path: 'static\\upload\\266005473a95b69207dd145241439db0',
    size: 136586 } ]
複製代碼

能夠看到表單數據和文件都已經處理完畢。

相關文章
相關標籤/搜索