Node.js 本机文件上传表单

Node.js native file upload form

我有一个问题:有什么方法可以在 node.js 中创建 native 文件上传系统吗?没有 multer、busboy 等模块。我只想从文件形式保存它。喜欢:

<form action="/files" method="post">
     <input type="file" name="file1">
</form>

可以在 node.js 中本地访问此文件吗?也许我错了,但如果这个模块做到了,那一定是可能的,对吧?

有可能。下面是一个例子。

const http = require('http');
const fs = require('fs');

const filename = "logo.jpg";
const boundary = "MyBoundary12345";

fs.readFile(filename, function (err, content) {
    if (err) {
        console.log(err);
        return
    }

    let data = "";
    data += "--" + boundary + "\r\n";
    data += "Content-Disposition: form-data; name=\"file1\"; filename=\"" + filename + "\"\r\nContent-Type: image/jpeg\r\n";
    data += "Content-Type:application/octet-stream\r\n\r\n";

    const payload = Buffer.concat([
        Buffer.from(data, "utf8"),
        Buffer.from(content, 'binary'),
        Buffer.from("\r\n--" + boundary + "--\r\n", "utf8"),
    ]);

    const options = {
        host: "localhost",
        port: 8080,
        path: "/upload",
        method: 'POST',
        headers: {
            "Content-Type": "multipart/form-data; boundary=" + boundary,
        },
    }

    const chunks = [];
    const req = http.request(options, response => {
        response.on('data', (chunk) => chunks.push(chunk));
        response.on('end', () => console.log(Buffer.concat(chunks).toString()));
    });

    req.write(payload)
    req.end()
})

这个问题很有意思。我想知道为什么还没有回答(4 年零 9 个月)。