Character limit uploading base64 image to nodejs server

I’m trying to upload an image (in base64 format) to a node server through element in html:

<form action="/" method="POST">
  <input type="file" id="image_input" accept="image/jpeg, image/png, image/jpg" multiple=true> 
  <input type=hidden id=images1 name=images>
<input type="submit">
</form>
<script>
const image_input = document.querySelector("#image_input");

image_input.addEventListener("change", function() {
  const file_reader = new FileReader();
  file_reader.addEventListener("load", () => {
    const uploaded_image = file_reader.result;
    	document.getElementById("images1").value = uploaded_image
  });
  file_reader.readAsDataURL(this.files[0]);
});
</script>

Node.JS:

app.post("/", (req,res)=>{
    console.log(req.body.images);
})

It throws this error:

PayloadTooLargeError: request entity too large

Is there any way to increase how many characters I can send with post? Or is there a more compressed image format I can use instead?

Is there any reason you need to send the image as base64 data? multipart/form-data is kinda better in this situation and you probably won’t have any problems with limit uploading.

You can use multer as middleware

const multer = require('multer');
const upload = multer();

app.post("/", upload.single('image_input'), (req, res) => {
  // just so you know that req.file contains information about the uploaded file
  console.log(req.file);
});

That way you don’t have to convert the image to base64 anymore, besides being more effective too.

2 Likes

Do you know how to decode the file once multer uploads it to a file? I’m getting this:

g�Y�ͬ\�l>�*;�Ymgǚ;{f�*�[�!�q�cP�N˪�L>gU5hp)�h�8�tC�;�֘af5]�=�/�6kh��o�:}�l[�ڻ:UEm3�6
�ծ�j�L�Rj^Hglk�Km[@=�TQC�@*Z�T�t.giuZ�V�*�+

How do I turn that into an image file?

1 Like

This is how the file in raw binary looks like, you just need to write it to an image file. We can use fs module’s writeFile function to write the data.

const express = require('express');
const multer = require('multer');
const fs = require('fs');

const app = express();
const upload = multer(); 

app.post("/", upload.single('image_input'), (req, res) => {
    // Make a little check to see if the file is present
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }

    // Than you write the file
    fs.writeFile('uploaded_image.jpg', req.file.buffer, function(err) {
        if (err) {
            return res.status(500).send(err);
        }

        res.send('File uploaded successfully.');
    });
});

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.