原生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;
}
if (
file.type != "image/png" &&
file.type != "image/jpeg" &&
file.type != "image/gif" &&
file.type != "image/jpg"
) {
this.$buefy.notification.open({
message: `不支持该文件类型`,
duration: 3500,
progressBar: true,
type: "is-danger",
pauseOnHover: true,
position: "is-bottom-left",
});
return false;
}
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(); },
初版效果


浙公网安备 33010602011771号