原生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(); },
初版效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗