vue+elementui+nodejs 实现图片的上传

今天写瀑布流的时候,想自己用node创建后台服务。就写了图片上传的demo。自己在过程中学到很多。

vue文件代码:

<template>

  <div>

    菜单管理

    <el-upload

      class="upload-demo"

      action

      :auto-upload="false"

      :on-remove="handleRemove"

      :before-remove="beforeRemove"

      multiple

      :on-change="onChange"

    >

   <el-button icon="el-icon-upload" type="primary" style="margin-top: 20px;"  >选择</el-button      >

    </el-upload>

    <el-button

      icon="el-icon-upload"

      type="primary"

      style="margin-top: 20px;"

      @click="submitUpload"

      >上传</el-button

    >

  </div>

</template>

<script>

import axios from 'axios'

export default {

  data () {

    return {

      fileList: []

    }

  },

  methods: {

    submitUpload () {

      let formData = new FormData()

      this.fileList.forEach(file => {

        formData.append('file', file)

      })

      axios.post('http://localhost:4000/saveImage', formData).then(res => {})

    },

    handleRemove (file, fileList) {},

    beforeRemove (file, fileList) {},

    onChange (file, fileList) {

      if (file) {

        this.fileList.push(file.raw)

      }

    }

  }

}

</script>

<style></style>


nodejs代码:

所有的require模块都需要 npm install 模块 -s

const cors = require('koa2-cors')  //解决跨域 本文是http://localhost:8080 向http://localhost:4000 跨域请求

var fsr = require('fs-extra') //把图片从临时文件夹转移到指定文件夹

var Koa = require('koa')

const getSize = require('image-size') // 获取图片宽高

var Router = require('koa-router')

var fs = require('fs')

const koaStatic = require('koa-static')

const path = require('path')

var body = require('koa-body')

const bodyParse = require('koa-bodyparser')

const app = new Koa()

//跨域设置

app.use(

  cors({

    origin: "*",

    maxAge: 5,

    credentials: true,

    withCredentials: true,

    allowMethods: ['GET', 'POST'],

    allowHeaders: ['Content-Type', 'Authorization', 'Accept']

  })

)


app.use(koaStatic(path.join(__dirname, './upload/')))//设置  图片静态服务器 设置之后就可以直接访问http://localhost:4000/male.jpg图片了

app.use(

  body({

    multipart: true

  })

)//设置可以多文件上传

app.use(bodyParse())

var router = new Router()

router.post('/saveImage', body(), async (ctx, next) => {

  var data = ctx.request.files.file

  const dest = path.join(__dirname, 'upload', data.name)

  fsr.move(data.path, dest) 

  var width = getSize('./upload/' + data.name).width

  var height = getSize('./upload/' + data.name).height

  let url = 'http://localhost:4000/' + data.name + '?' + width + '*' + height

  ctx.body = {

    path: data.path,

    name: data.name,

    url: url

  }

})

app.use(router.routes()).use(router.allowedMethods())

app.listen(4000)

console.log('server started at http://localhost:4000')

结果展示:


在实现过程中 https://www.jianshu.com/p/901084d32de2这篇文章给了我很大的帮助

这篇文章解释的很详细。推荐一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容