[英]multer + socket.io + FormData sending file issue
我正在尝试使用 socket.io 发送图片并遇到此错误
返回 req.headers['transfer-encoding']:== undefined || 类型错误:无法读取未定义的属性“传输编码”
在我使用 axios + multer 之前,它工作得很好
所以有我的代码
服务器:
const fileSchema = new mongoose.Schema({
originalname: String,
filename: String,
path: String,
mimetype: String,
});
const File = mongoose.model("File", fileSchema);
socket.on("ROOM:FILE_UPLOAD", (formData) => {
upload.single("image")(formData, null, (err) => {
if (err) console.log(err);
else {
const originalname = formData.originalname;
const filename = formData.filename;
const path = formData.path;
const mimetype = formData.mimetype;
const file = new File({
originalname,
filename,
path,
mimetype,
});
file.save((err, image) => {
if (err) {
console.error(err);
} else {
console.log(`Image saved to MongoDB: ${image._id}`);
}
});
}
});
});
客户:
const [file, setFile] = useState(null);
function handleFileSelect(event: any) {
setFile(event.target.files[0]);
}
function sendMsg(event) {
event.preventDefault();
const formData = new FormData();
formData.append("image", file);
socket.emit("ROOM:FILE_UPLOAD", formData);
}
return (
<div className="container">
<div className="row">
<form encType="multipart/form-data" onSubmit={upload}>
<input
type="file"
accept="image/*"
onChange={handleFileSelect}
name="image"
/>
<button onClick={sendMsg}>send</button>
</form>
</div>
</div>
);
我在哪里弄错了?
所以,从一开始就通过 sockets 发送图片作为消息是个坏主意,这会增加服务器负载,所以我会使用另一种类似于电报的算法,文档上有链接。 没有任何理由尝试修复此错误,因为主要错误是决定如何在聊天中发送图片
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.