Skip to main content

如何上传文件

¥How to upload a file

文件 可以按原样发送:

¥Files can be sent as is:

<!doctype html>
<html lang="en">
<body>
<input type="file" onchange="upload(this.files)" />

<script src="/path/to/socket.io.js"></script>
<script>
const socket = io();

function upload(files) {
socket.emit("upload", files[0], (status) => {
console.log(status);
});
}
</script>
</body>
</html>

该文件将在服务器端以 缓冲 形式接收:

¥The file will be received as a Buffer on the server side:

import { writeFile } from "fs";

io.on("connection", (socket) => {
socket.on("upload", (file, callback) => {
console.log(file); // <Buffer 25 50 44 ...>

// save the content to the disk, for example
writeFile("/tmp/upload", file, (err) => {
callback({ message: err ? "failure" : "success" });
});
});
});

补充注意

¥Additional notes

maxHttpBufferSize 限制

¥maxHttpBufferSize limit

上传文件时,你可能会达到 maxHttpBufferSize 值,该值是允许的最大消息大小(以字节为单位)。默认为 1 MB。

¥While uploading a file, you might reach the maxHttpBufferSize value, which is the maximum allowed message size in bytes. It defaults to 1 MB.

你可以根据你的用例增加此值:

¥You can increase this value, according to your use case:

import { Server } from "socket.io";

const io = new Server({
maxHttpBufferSize: 1e8 // 100 MB
});

参考:maxHttpBufferSize 选项

¥Reference: maxHttpBufferSize option

通过电线

¥Over the wire

与其他二进制结构(ArrayBuffer斑点)一样,emit() 方法的参数将作为两个 WebSocket 帧通过线路发送:

¥Like other binary structures (ArrayBuffer, Blob), the arguments of the emit() method will be sent as two WebSocket frames over the wire:

首先,一个文本框架:

¥First, a text frame:

451-["upload",{"_placeholder":true,"num":0}]
||||└─ JSON-encoded payload with placeholders for binary attachments
||||
|||└─ separator
||└─ number of binary attachments
|└─ socket.io BINARY EVENT packet type
└─ engine.io MESSAGE packet type

然后是一个二进制帧(每个二进制结构一个):

¥And then a binary frame (one per binary structure):

<0x25 0x50 0x44 ...>

根据你的用例,你可以使用 自定义解析器 来更改此行为。

¥Depending on your use case, you may change this behavior by using a custom parser.