vue实现图片的上传和删除

[TOC]

1 UI库使用ElementUI

安装ElementUI

$ npm install element-ui --save-dev

vue加载ElementUI

import ElementUI from 'element-ui' // 导入elementui库
import 'element-ui/lib/theme-chalk/index.css' // 导入样式

Vue.use(ElementUI)

组件中使用

<template>
    <!-- 图片上传控件 -->
    <el-upload
        :action="uploadUrl"        
        list-type="picture-card"
        :limit="5"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleUpdateSuccess">
        <i class="el-icon-plus"></i>
    </el-upload>
    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      imgs: [], // 已上传图片列表
      uploadUrl: '/api/updateImg', // 图片上传接口地址,自定义
      dialogImageUrl: '', // 预览图片地址
      dialogVisible: false // 图片预览
    }
  },
  methods: {
    // 图片预览
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 图片上传成功
     * 当上传图片时,ElementUI生成图片的Blob对象,然后本地显示
     * post请求action指定的api接口
     * 接口返回JSON数据{state: 'success', img: 'xxxxxxxxxxxxx.xxx'}
     * 把得到的img存储进this.imgs中
     */
    handleUpdateSuccess (res, file, fileList) {
      if (res.state === 'success') {
        this.imgs.push(res.img) // this.imgs记录已上传成功的图片
      }
    },
    /**
     * 图片删除
     * 由于图片存储在服务器上,ElementUI图片删除只是删除本地显示
     * 所以需要调用服务器图片删除接口,我这里接口为'/api/deleteImg'
     * 接口返回JSON格式数据:{state: 'success'}
     * 然后从this.imgs中删除图片记录
     * this.$http.post为axios的请求方法,不做详细说明
     */
    handleRemove (file, fileList) {
      const IMG = file.response.img
      const INDEX = this.imgs.indexOf(IMG)
      this.$http.post('/api/deleteImg', {img: IMG}).then((res) => { // 服务器删除图片
        const data = res.data
        if (data.state === 'success') {
          this.imgs.splice(INDEX, 1) // 从this.imgs中删除图片记录
        }
      })
    }
  }
}
</script>

前端配置就这么多了,关于 中的配置项,可以自行查看ElementUI文档说明,下面我们就来写后台接口。后台接口只要就是两个 '/api/updateImg':上传图片接口;'/api/deleteImg':删除图片接口

2 后台使用Express + formidable

Express安装和使用这里就不详细说明,主要是formidable使用,formidable是一个用来解析表单(尤其文件上传)的node模块

安装 formidable

$ npm install formidable --save-dev

后台路由配置, 新建一个api.js作为接口模块,然后在app.js中

const api = require('./api');
app.use('/api', api);

api.js接口模块

const express = require('express');
const router = express.Router();

/**
 * 上传图片
 */
router.post('/updateImg', function(req, res, next) {
  const form = new formidable.IncomingForm();
  form.uploadDir = path.join(__dirname, '../upload/img'); // 设置图片路径
  form.keepExtensions = true; // 保持扩展名
  form.parse(req, function(err, fields, files) {
    if (err) throw err;
    const saveImgName = files.file.path.split("\\").pop(); // 图片名称
    res.json({state: 'success', img: saveImgName}); // 已保存,返回JSON
  });
})
/**
 * 删除图片
 */
router.post('/deleteImg', function(req, res, next) {
  const params = req.body;
  const deleteImgName = params.img; // 图片名称
  const imgPath = path.join(__dirname, `../upload/img/${deleteImgName}`); // 图片路径
  fs.unlink(imgPath, () => {
    res.json({state: 'success'}); // 已删除,返回JSON
  })
})

module.exports = router;

猜你喜欢

转载自www.cnblogs.com/roddy/p/9244057.html