我有一個允許用戶上傳圖像的輸入,我如何才能把這個圖像發送到服務器上呢?
到目前為止,我的情況是:
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)
你要做的第一件事就是序列化圖像。這意味著我們需要將圖像文件轉換成可以通過互聯網傳輸的內容,在這種情況下,最好的選擇是
base64
編碼。以下是您的解決方案:Client-side
Server-side