How to upload an image to Nodejs?

Asked

Viewed 259 times

2

Good afternoon,

I want to make a POST Request of the client in JAVASCRIPT with DATA Send (file . jpg) in date URL for the NODEJS server.

[Client] - Javascript

    finalImg.onload = function(event){
        var request = new XMLHttpRequest();
        request.onload = function (event) {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        };

        request.open('post', '/setimageprofile', true);
        request.setRequestHeader('Content-type', 'image/JPEG;charset=UTF-8');
        request.send(finalImg);
    }

[Server] - Nodejs

app.post('/setimageprofile', function(req, res) {
    //var request_data = '';
    var writable = fs.createWriteStream('./client_imgs/getusername.jpg');
    req.on('data', function(data){
        writable.write(data);
    });

    req.on('end', function() {
        writable.end();
    });
});

[Problem] When I open the file ./client_imgs/getusername.jpg with the image viewer I have the error "We do not support this file format". Apparently I should cast a date that is being sent to me, am I right? If yes, how to do?

[Note] On the server I have,

const bodyParser = require("body-parser");
var express = require('express');
var fs = require('fs');
var url = require('url');
var app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
  • You can put the solution you found in a same answer

1 answer

2


[UPDATE] I found solution

[server]

app.post('/setimageprofile', function(req, res) {
    var request_data = '';
    var writable = fs.createWriteStream('./client_imgs/getusername.png', 'base64');
    req.on('data', function(data){
        request_data += data;
    });

    req.on('end', function() {
        request_data = JSON.parse(request_data).data;
        var base64Data = request_data.replace(/^data:image\/png;base64,/, "");
        console.log(base64Data);
        writable.write(base64Data);

        writable.end();
    });
});

[client]

var data = { data : finalImgURL};
        console.log('type: ' + dataTypeFromParent);
        // post - send image to server
        finalImg.onload = function(event){
            var request = new XMLHttpRequest();
            request.onload = function (event) {
                if (request.readyState == 4 && request.status == 200) {
                    console.log(request.responseText);
                }
            };

            request.open('post', '/setimageprofile', true);
            request.setRequestHeader('Content-type', 'plain/text;charset=UTF-8');
            request.send(JSON.stringify(data));
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.