element-ui上传和node.js服务器multer实现图片文件上传功能

1、第一个版本,基础版,直接跨域,未做代理。
前端

  <el-upload
  class="upload-demo"
  action="http://localhost:3000/upload"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kbdiv>
el-upload>

后台express,app.js

// app.js
var uploaderRouter =  require('./routes/upload')

app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method == 'OPTIONS') {
      res.send(200);
  }else {
      next();
  }
});

app.use('/upload', uploaderRouter);

upload.js

// routes/upload.js
var express = require('express');
var router = express.Router();
const multer = require('multer')

const storage = multer.diskStorage({
  //存储的位置
  destination(req, file, cb){
      cb(null, 'public/upload/')
  },
  //文件名字的确定 multer默认帮我们取一个没有扩展名的文件名,因此需要我们自己定义
  filename(req, file, cb){
      cb(null, Date.now() + file.originalname)
  }
})
const upload = multer({storage})
 router.post('/', upload.single('file'), (req, res) =>{
    //给客户端返回图片的访问地址 域名 + 文件名字 
    //因为在 app.js文件里面我们已经向外暴漏了存储图片的文件夹 uploa
     const url = 'http://localhost:3000/upload/' + req.file.filename
     res.json({url})
 })

module.exports = router;

2、第二个版本,前端使用代理配置,来解决跨域,但是配置完了要重启 npm run dev 不然,还是报错404
后端可以去掉通配符的跨域代码,其他代码不用改,改前端代码

   <el-upload
  class="upload-demo"
  action="/api/upload"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kbdiv>
el-upload>

webpack跨域代理设置:

  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      ws: false
    },

参考:
1、多文件图片上传处理方式:
https://www.cnblogs.com/xiaoliwang/p/10190780.html

你可能感兴趣的:(Node.js,前端技术积累)