【发布时间】:2021-07-07 02:03:01
【问题描述】:
我有一个让用户上传图片的输入,我如何才能将此图片发送到服务器?
这是我目前所拥有的:
server.js
const express = require("express");
const path = require("path");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
var PORT = 7778;
app.use(express.static(path.join(__dirname)));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
io.on("connection", (socket) => {
socket.on("send-img", () => {
console.log("img recieved");
});
});
http.listen(PORT, () => {
console.log("Server started on port: " + PORT);
});
client.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Works!</h1>
<input type="file" accept=".jpg, jpeg, png" multiple id="img-uplaod" />
<button id="img-submit">Click Me</button>
</body>
<script>
const socket = io();
document.getElementById("img-submit").onclick = function () {
socket.emit("send-img");
};
</script>
</html>
下面发布的答案几乎可以工作,但我收到此错误:
at Object.openSync (fs.js:443:3)
at Object.writeFileSync (fs.js:1194:35)
at Socket.socket.on (/home/pyroot/Desktop/main-dev/projects-main/sell-anything/server.js:19:6)
at Socket.emit (events.js:198:13)
at /home/pyroot/Desktop/main-dev/projects-main/sell-anything/node_modules/socket.io/lib/socket.js:528:12
at process._tickCallback (internal/process/next_tick.js:61:11)
【问题讨论】:
标签: node.js file-upload socket.io