1. 程式人生 > 實用技巧 >node koa-multer vue mysql檔案上傳刪除

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); }); },

資料庫

記錄