2

i have a question: Is there any way to create native file upload system in node.js? Without modules like multer, busboy and others. I just want save it from file form. Like:

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

It's possible to acces this file native in node.js? Maybe im wrong, but if this modules do it, it must be possible, right?

user3075373
  • 44
  • 1
  • 4
  • 19
  • well, of course, most of those modules are written in what you call "native" node.js. – Kevin B Jul 17 '15 at 14:23
  • possible duplicate of [Nodejs server that accepts POST requests](http://stackoverflow.com/questions/12006417/nodejs-server-that-accepts-post-requests) – stdob-- Jul 17 '15 at 14:29

1 Answers1

3

It is possible. An example is below.

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()
})

The question is interesting. I wonder why it is not already answered (4 years, 9 months).