天天看點

node+express+multer+vue+element-ui實作檔案上傳

實作方式 : ele-ui + express + multer

如果你能看到我這篇文章,很榮幸,你一定踩了很多坑,現在node的上傳普遍使用multer,這玩意,不同版本使用的方式還不太一樣,希望你看完這篇文章,能夠在臉上洋溢出幸福的笑容!

基于multer 1.41 版本實作的上傳系統

直接粘代碼

<el-form-item label="檔案" label-width="120px">
        <el-upload class="upload-demo" action="" :auto-upload="false" :limit="1" ref="upload" :http-request="upload" multiple>
          <el-button size="small" type="primary">模拟上傳2</el-button>
        </el-upload>
      </el-form-item>
 <el-button class="btn" size="small" type="primary" @click="upload">确定上傳2</el-button>
           
method中的方法—點選btn調用
upload() {
      const formData = new FormData()
      const file = this.$refs.upload.uploadFiles[0]
      const headerConfig = { headers: { 'Content-Type': 'multipart/form-data' }}
      if (!file) { // 若未選擇檔案
        alert('請選擇檔案')
        return
      }
      formData.append('file', file.raw)
      axios.post('http://localhost:5657/situation/upfile', formData, headerConfig).then(res => {
        console.log(res)
      })
    },
           

node部分,接收,并儲存

其中upfile檔案為json檔案,可以把函數暴露的部分注掉!
我這種寫法是暴露出來,讓其它檔案引用,如果可以直接執行,可以把 export default 注釋掉!
import app from '../../index.js'
import { upfile } from './upfile.js'
var multer = require('multer')
const uuidV1 = require('uuid/v1')
var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'upload/') // 儲存的路徑,備注:需要自己建立
  },
  filename: function(req, file, cb) {
    const fileFormat = (file.originalname).split('.') // 取字尾
    cb(null, uuidV1() + '.' + fileFormat[fileFormat.length - 1])
  } })
var upload = multer({ storage: storage })
export default file => {
  app.post('/situation/upfile', upload.single('file'), function(req, res, next) {
    upfile(res).then(ele => {
      res.send(ele)
    }).catch(err => {
      res.send(err, '---ree')
    })
  })
}

           
upfile.js 的代碼如下
export const upfile = async res => {
  const arr = {
    'code': 20000,
    'data': {
      'token': 'admin'
    }
  }
  return arr
}

           

繼續閱讀