Sunday, 1 July 2018

How to properly upload and save photo using Node.JS (no frameworks)

I'm adding photo uploading feature to my chat. I have POST parser from this answer, and little code that saves image to uploads directory.

var ext = exports.getFileExt(Object.keys(partsByName)[0]);
var time = (new Date()).getTime();
fs.writeFile("./img/user/upload_" + time + "." + ext,
    partsByName[Object.keys(partsByName)[0]], "binary", function (err) {
        if (!err) {
            res.writeHead(200, "OK", { "Content-Type": "text/html" });
            res.write(exports.wrapHTML(<title>, <html>, <font params>));
            res.end();
        } else {
            console.error(err);
            res.writeHead(500, "Internal Server Error");
            res.end();
        }
    });

Image saves with expected name, but it doesn't opens and I think there is incorrect encoding.

Source file start looks like this:

яШяа JFIF H H яб"Exif MM *

but newly saved file is different:

ээээ JFIF H H ээ"Exif MM *

UPD: Now I think that Cyrillic just lost when sending data. In console and browser they look as unknown character (stroked rectangle).



from How to properly upload and save photo using Node.JS (no frameworks)

No comments:

Post a Comment