Node.js原生文件上传表

人气:766 发布:2022-10-16 标签: file forms node.js upload native

问题描述

我有一个问题:有没有办法在node.js中创建原生文件上传系统?没有像穆特,餐童和其他模块。我只是想把它从文件格式中保存下来。点赞:

<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 + "
";
    data += "Content-Disposition: form-data; name="file1"; filename="" + filename + ""
Content-Type: image/jpeg
";
    data += "Content-Type:application/octet-stream

";

    const payload = Buffer.concat([
        Buffer.from(data, "utf8"),
        Buffer.from(content, 'binary'),
        Buffer.from("
--" + boundary + "--
", "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个月)。

390