Node.js本机文件上传表单

编程入门 行业动态 更新时间:2024-10-09 08:25:58

Node.js<a href=https://www.elefans.com/category/jswz/34/1766600.html style=本机文件上传表单"/>

Node.js本机文件上传表单

我有一个问题:有没有办法在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个月)。

更多推荐

Node.js本机文件上传表单

本文发布于:2024-05-07 06:00:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   表单   文件上传   Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!