个人小项目 Vue+node富文本编辑器之FormData上传文件

首先,看看前端按钮应该怎么触发上传
在这里插入图片描述
先设置一个按钮点击触发,type为file的输入框(input的display为none隐藏!),以选择本地文件。

第二步:再来写个方法, button代替input选择图片

onPickImg() {
  this.$refs.imgInput.click();
 },

第三步: 文件选择后, 后在页面上显示出来 转base64位的操作

getImg(event) {
  const files = event.target.files;
  let filename = files[0].name; //只有一个文件
  if (filename.lastIndexOf(".") <= 0) {
    this.$message.error("Please add a valid image!"); //判断图片是否有效
  }
  const fileReader = new FileReader(); //内置方法new FileReader()   读取文件
  fileReader.addEventListener("load", () => {
    this.imageUrl = fileReader.result;
  });
  fileReader.readAsDataURL(files[0]);
  this.image = files[0];
  //到这里后, 选择图片就可以显示出来了
  this.onUpload("image");
},

第四步: 上传文件了

onUpload(type) {
  let fd = new FormData(); //内置方法new FormData()  新建一个表格
  if (type == "image") {
    // fd.append("type", type);
    fd.append("file", this.image); //把image添加进去
    console.log(this.image); //(       第二次有效打印           )
    console.log(fd);
  } else if (type == "file") {
    fd.append("type", type);
    fd.append("file", this.file); //把image添加进去
    console.log(this.image); //(       第二次有效打印           )
    console.log(fd);
  }
  //封装的请求,调用
  insertEditor
    .uploadfile(fd)
    .then((res) => {
      //第一个参:this.postUrl就是上面保存好的要上传的地址
      console.log(res); //(      第三次有效打印    )
      //上传成功 , 后台返回了一个图片地址  转化一下 反斜杠转正斜杠
      this.imageUrl = res.data.url.replace(/\\/g, "/");;
      // 渲染图片
      // 生成img标签,并打上特殊唯一标识
      const fileTag = document.createElement("img");
      fileTag.src = this.imageUrl;
      fileTag.style = `max-height:600px; max-width:600px; vertical-align:top; padding:8px; display:inline-block;`;
      fileTag.title = this.image.name;
      const range = getSelection().getRangeAt(0);
      // 删除range里面的内容
      range.deleteContents();
      // console.log(range, node)
      // 插入节点
      range.insertNode(fileTag);
      // 插入光标
      // getSelection().addRange(getSelection().getRangeAt(0));
    })
    .catch((error) => {
      console.log(error);
    });
},

后端node接口怎么接收?

npm install multiparty -save
先npm下载导入multiparty

const multiparty = require('multiparty')
// 上传图片
router.post('/v1/editor/uploadFile', function (req, res) {
  let form = new multiparty.Form();
  var path = require('path');
  // 文件保存的路径
  form.uploadDir = path.resolve(__dirname, '../public/images');
  form.keepExtensions = true;   //是否保留后缀
  form.autoFiels = true;       //启用文件事件,并禁用部分文件事件,如果监听文件事件,则默认为true。
  form.parse(req, function (err, fields, files) {  //其中fields表示你提交的表单数据对象,files表示你提交的文件对象
    // console.log(fields, files);
    if (err) {
      res.json({
        code: -1,
        success: false,
        msg: "上传失败!" + err
      });
    } else {
      res.json({
        code: 0,
        success: true,
        msg: '上传成功',
        url: "http://localhost:3000" + files.file[0].path.split("public")[1]
      })
    }
  });
});

注意,这里有个重要的点!!如果传过来的参数拿不到,那你将上传不了,为什么会拿不到呢?你传参格式不对,formData本身就是个对象,insertEditor.uploadfile(fd)要这样传,insertEditor.uploadfile({fd})这样就会出错拿不到!

追后看一下演示效果
点击按钮
在这里插入图片描述
选择图片
在这里插入图片描述

上传成功,显示在富文本输入框
在这里插入图片描述
图片储存位置,在配置路径下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值