A
A
Alexander Degtyarev2017-07-26 21:53:04
JavaScript
Alexander Degtyarev, 2017-07-26 21:53:04

How to send image to nodejs?

Please help how to pass ajax via input[type='file'] data in nodejs. What comes, weighs more than necessary and does not open like a picture.

'use strict'

var fs = require('fs');
var express = require('express');
var cors = require('cors');
var app = express();

app.use(cors());

app.post('/', function (req, res) {
    var data = '';

    req.on('data', function (chank) {
        data += chank;
    }).on('end', function () {
        fs.writeFile('file1.jpg', data, function (err) {
            if (err) console.log(err.message);
        });
    });
});

app.listen(8001);
<!doctype html>
<title>API Testing</title>

<input type="file" name="file">
<img src="" alt="photo one">

<script>
    'use strick'

    var file_input = document.querySelector('input');
    var img_url = document.querySelector('img');
    var xhr = new XMLHttpRequest();

    xhr.open('post', 'http://localhost:8001/', true);

    xhr.addEventListener('load', function () {

        console.log(xhr.responseText);
        img_url.src = xhr.responseText;
    });

    file_input.addEventListener('change', function () {
        xhr.setRequestHeader('Content-Type', 'multipart/form-data');
        xhr.send(file_input.files[0]);
    });

</script>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Abcdefgk, 2017-07-26
@alexdeg

AJAX sends a stream, it is necessary to accept - as a stream.

var stream = fs.createWriteStream('... тут абсолютный путь/file.jpg');
req.pipe(stream);

stream.on('end', () => res.end());
stream.on('error', (err) => {...});

If only a picture - it is not necessary to encode.

H
Hazrat Hajikerimov, 2017-07-26
@hazratgs

If the request body size is large, use the body-parser package

const bodyParser = require('body-parser')
. . .
app.use(bodyParser.urlencoded({
    extended: true,
    limit: '5mb' // лимит
}))
. . .

D
Dmitry Belyaev, 2017-07-26
@bingo347

It is not necessary to convert binary data to a string, multibyte encodings are not friendly with this
Option 1 - add chunks to an array and merge them using Buffer.concat
Option 2 - open write stream to a file and make req.pipe into it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question