vue配合node实现图片上传和删除功能

116 阅读1分钟

前端选用elementUI 图片上传组件

pic.png node后端接收传过来的图片

图片上传

uploadPic = async (ctx) => {
  const { file } = ctx.request.files
  if (file) {
    // 加工图片路径
    let path = file.filepath
    let index = path.lastIndexOf('/')
    let url = path.slice(0, index)
    ctx.body = {
      code: 200,
      msg: '商品图片上传成功',
      result: {
        url,
        name: file.newFilename
      }
    }
  } else {
    ctx.body = {
      code: 500,
      msg: '图片上传异常'
    }
  }

}

elementUI提供了上传成功时的钩子,在钩子里保存当前上传图片的路径和文件名(删除时需要传递对应参数)

图片删除

前端

 this.$http({
        method: 'post',
        url: '/upload/del_pic',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })

注意这里要特地设置post中的form-data类型 后端

deletePic = async (ctx) => {
  console.log('body', ctx)
  const { url, name } = ctx.request.body
  var files = [];
  if (fs.existsSync(url)) {    //判断给定的路径是否存在
    files = fs.readdirSync(url);    //返回文件和子目录的数组
    files.forEach(function (file, index) {
      var curPath = path.join(url, file);
      if (fs.statSync(curPath).isDirectory()) { //同步读取文件夹文件,如果是文件夹,则函数回调
        deleteFile(curPath, name);
      } else {
        if (file.indexOf(name) > -1) {    //是指定文件,则删除
          fs.unlinkSync(curPath);
          console.log("删除文件:" + curPath);
          ctx.body = {
            code: 200,
            msg: '删除成功'
          }
        }
      }
    })
  } else {
    console.log("给定的路径不存在!");
    ctx.body = {
      code: 500,
      msg: '给定的路径不存在!'
    }
  }
}