原生input-file图片上传,转base64存储到node或socket广播对应房间

2021/12/28 17:37:37

本文主要是介绍原生input-file图片上传,转base64存储到node或socket广播对应房间,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

做的第二版聊天室demo来玩,比第一版新增socket.io加入房间功能

基于前端:vue2+buefy(超喜欢这个ui,虽然没中文文档)+简单媒体查询响应式

服务端:node+express+socket.io(很优秀的第三方api)

只记录下自己的聊天室图片上传主要代码

template部分

上传图片,iconfont与input-file隐藏处理

<i class="iconfont icon-photo pr-4 uploadImg">
                <input
                  class="uploadImgInput"
                  type="file"
                  @change="addImg"
                  ref="inputer"
                  accept="image/png,image/jpeg,image/gif,image/jpg"
                />
              </i>

style处理input-flie占位隐藏

.uploadImg {
    position: relative;
    .uploadImgInput {
        cursor: pointer !important;
        width: 1.46rem;
        height: 100%;
        z-index: 10000;
        opacity: 0;
        position: absolute;
        left: 0;
    }
}

methods,通过HTML5的new FileReader(),将图片转换base64传递socket服务端

 addImg(e) {
      const input = e.target;
      const files = e.target.files;
      if (files && files[0]) {
        const file = files[0];
        if (file.size > 1024 * 1024 * 3) {
          this.$buefy.notification.open({
            message: `文件大小不能超过3M`,
            duration: 3500,
            progressBar: true,
            type: "is-danger",
            pauseOnHover: true,
            position: "is-bottom-left",
          });
          input.value = "";
          return false;
        } else {
          console.log(files[0]);
          this.uploadImg(files[0]);
        }
      }
    },
    //上传图片
    uploadImg(file) {
      let imgName = file.name.split(".")[0].toString();
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onloadend = () => {
        this.$socket.emit("sendImg", {
          reader: reader.result,
          imgName,
        });
      };
    },

服务端socket.io处理,注释掉的是存本地的,我这里不存只做对应房间广播中转回客户端

 socket.on("sendImg", ({ reader, imgName }) => {
        // const splitted = reader.split(';base64,');
        // const format = splitted[0].split('/')[1];
        // fs.writeFileSync(`./images/${imgName}.` + format, splitted[1], { encoding: 'base64' });
        const user = getCurrentUser(socket.id);
        io.to(user.roomName).emit('img', sendImg(user.userName, reader, imgName))
    });

客户端socket监听

img(data) {
      console.log("img", data);
      const isMe = this.userName === data.userName;
      const res = Object.assign(data, { isMe });
      this.msgList.push(res);
      this.scrollFunc();
    },

初版效果

 

 



这篇关于原生input-file图片上传,转base64存储到node或socket广播对应房间的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程