欢迎来到ZeroAO的博客

竹杖芒鞋轻胜马,谁怕?一蓑烟雨任平生。
扩大
缩小

node koa-multer vue mysql文件上传删除

在项目中要管理图片文件,本项目中MySQL中存储是地址,利用koa-multer管理上传图片

首先安装引入

npm install koa-static --save

 

新建upload.js文件

var router = require('koa-router')();
var koaBody = require('koa-body');
const multer=require('koa-multer')
// 适配ueditor百度编辑器
const ueditor = require('koa2-ueditor');
const fs = require('fs')
//文件上传
//配置
var storage = multer.diskStorage({
  //文件保存路径
  destination: function (req, file, cb) {
    cb(null, 'upload/')
  },
  //修改文件名称
  filename: function (req, file, cb) {
    var fileFormat = (file.originalname).split(".");  //以点分割成数组,数组的最后一项就是后缀名
    cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
  }
})
//加载配置
var upload = multer({ storage: storage });
router.post('/uploadFile',upload.single('file'),async(ctx,next)=>{
  ctx.body = {
    imgUrl: ctx.req.file.filename//返回文件名
   
  }
})

/**
 * 删除图片接口
 */
router.post('/deleteImg',koaBody(),async(ctx,next)=>{
  let file = ctx.request.body.filename
  // unlinkSync删除 fs.unlinkSync(
'./upload/'+file) ctx.body={ msg: '删除文件成功!' } }) // 配置编辑器上传图片接口 router.all('/editorUpload', ueditor(['upload', { // 上传图片的格式 "imageAllowFiles": [".png", ".jpg", ".jpeg"], // 最后保存的文件路径 "imagePathFormat": "/ueditor/{yyyy}{mm}{dd}/{filename}" }] )); module.exports = router;

 

 

前端用的element ui的el-upload组件

https://element.eleme.cn/#/zh-CN/component/upload

<!-- 查看图片弹框 -->
    <el-dialog
      title="查看图片弹框"
      :visible.sync="imgDialogVisible"
      :before-close="imgHandleClose"
      width="50%"
    >
      <el-upload
        :action="API_ROOT + '/uploadFile'"
        list-type="picture-card"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="imgHandleClose">取 消</el-button>
        <el-button type="primary" @click="imgHandleClose">确 定</el-button>
      </span>
    </el-dialog>

函数

// 查看图片弹框
    openOrderImg(e) {
      this.imgDialogVisible = true;
      this.imgRuleForm.order_id = e.order_id;
      let file_list = [];
      if (e.order_img) {
        file_list = e.order_img.substring(1).split(",");
        let item = {};
        file_list.forEach((i) => {
          item = {};
          if (i != "") {
            item.uid = Date.parse(new Date()) + Math.random() * 10;
            item.name = i;
            item.url = this.API_ROOT + "/" + i;
          }
          this.fileList.push(item);
        });
      } else {
        this.fileList = [];
      }
    },
    // 关闭弹框查看图片弹框
    imgHandleClose() {
      this.fileList = [];
      // console.log(1);
      this.imgDialogVisible = false;
      // this.$message.info("您以取消上传");
      // clearFiles();
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
      
      file.name = res.imgUrl;
    // 将json格式的转字符串存到数据库 let fileListStr
= ""; fileList.forEach((item) => { fileListStr += "," + item.name; }); let parmas = { order_id: this.imgRuleForm.order_id, order_img: fileListStr, }; this.$post("/wechat/orderImg", parmas) .then((res) => { this.$message.success(response.message); this.list(); }) .catch((err) => { // this.$message.error("上传成功"); this.list(); }); }, // 删除图片 handleRemove(file, fileList) { console.log(file, fileList); let fileListStr = ""; fileList.forEach((item) => { fileListStr += "," + item.name; }); let parmas = { order_id: this.imgRuleForm.order_id, order_img: fileListStr, };
    // 删除数据库记录
this.$post("/wechat/orderImg", parmas) .then((res) => { this.$message.success(response.message); this.list(); }) .catch((err) => { // this.$message.error("已修改"); this.list(); }); this.$post("/deleteImg", { filename: file.name }) .then((res) => { console.log(res); }) .catch((res) => { console.log(res); }); },

数据库

 

 记录

 

posted on 2020-12-01 15:38  Zeroao  阅读(424)  评论(0编辑  收藏  举报

导航

Live2D