最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js本机文件上传表单

网站源码admin16浏览0评论

Node.js本机文件上传表单

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个月)。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论