node+express+multer+vue+element-ui实现文件上传

10 篇文章 1 订阅

实现方式 : 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
}

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值