天天看点

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
}

           

继续阅读