Node.js原生文件上传表单



我有一个问题:有没有办法在node.js中创建本地文件上传系统?没有像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 + "rn";
    data += "Content-Disposition: form-data; name="file1"; filename="" + filename + ""rnContent-Type: image/jpegrn";
    data += "Content-Type:application/octet-streamrnrn";
    const payload = Buffer.concat([
        Buffer.from(data, "utf8"),
        Buffer.from(content, 'binary'),
        Buffer.from("rn--" + boundary + "--rn", "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个月)。

相关内容

最新更新