Home>

Send the Base64 encoded image from the client in JSON,
I want to receive it at the server.

Problems encountered, things you tried Problem

To check if JSON is properly received on the server side, useconsole.log (req.body)
When trying to display on the console
{}
It was only displayed and seemed not to be able to receive JSON.

Try it

-When I confirmed that the client side developer tool was able to encode it properly, there seemed to be no problem.

I tried

console.log (req.body)withconsole.log (req.body.data), butundefind.

I tried the method using

body-parser, but it was not.

Source code Server side
var createError = require ('http-errors');
var express = require ('express');
var path = require ('path');
var cookieParser = require ('cookie-parser');
var logger = require ('morgan');
var indexRouter = require ('./ routes/index');
var usersRouter = require ('./ routes/users');
var app = express ();
// view engine setup
app.set ('views', path.join (__ dirname, 'views'));
app.set ('view engine', 'jade');
app.use (logger ('dev'));
app.use (express.json ());
app.use (express.urlencoded ({extended: false}));
app.use (cookieParser ());
app.use (express.static (path.join (__ dirname, 'public')));
app.use ('/', indexRouter);
app.use ('/ users', usersRouter);
// catch 404 and forward to error handler
app.use (function (req, res, next) {
  next (createError (404));
});
// error handler
app.use (function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get ('env') === 'development'? err: {};
  // render the error page
  res.status (err.status || 500);
  res.render ('error');
});

app.listen (8080);
module.exports = app;
// const model = await cocoSsd.load ();
var express = require ('express');
var router = express.Router ();
router.use (express.json ());
router.use (express.urlencoded ({extended: true}));
// Transit to the image upload screen
router.get ('/', function (req, res, next) {res.sendfile ("./ public/index.html");
});
// Where JSON is sent from the client
router.post ("/ upload", function (req, res, next) {
  console.log (req.body);
  // Hereafter omitted
});
module.exports = router;
Client side
<! DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <script
        src = "https://code.jquery.com/jquery-3.4.1.min.js"
        integrity = "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo ="
        crossorigin = "anonymous">
    </script>
    <title>Upload image</title>
</head>
<body>
        
            Upload image
        
        <!-File selection button->

    <form enctype = "multipart/form-data" method = "post">
      <input type = "file" name = "userfile" accept = "image/*">
    </form>
  
  <!-Thumbnail display area->
  <canvas width = "0" height = "0"></canvas>
  <!-Upload start button->
  <button>Post</button>
  <!-Below, javascript->
  <script type = "text/javascript">
  $(function () {
    var file = null;// selected file
    const THUMBNAIL_WIDTH = 640;// Horizontal length after image resizing
    const THUMBNAIL_HEIGHT = 480;// Vertical length after image resizing
    var base64;// Substitute this variable when Base64 encoded
    // Once the file is selected
    $('input [type = file]'). change (function () {
      // get the file
      file = $(this) .prop ('files') [0];
      // Determine if the selected file is an image
      if (file.type! = 'image/jpeg'&&file.type! = 'image/png') {
        // end if not an image
        file = null;
        blob = null;
        return;
      }
      // resize the image
      var image = new Image ();
      var reader = new FileReader ();
      reader.onload = function (e) {image.onload = function () {
          var width, height;
            width = THUMBNAIL_WIDTH;
            height = THUMBNAIL_HEIGHT;
          // Change the size of the canvas for thumbnail drawing to the value declared as a constant
          var canvas = $('# canvas')
                       .attr ('width', THUMBNAIL_WIDTH)
                       .attr ('height', THUMBNAIL_HEIGHT);
          var ctx = canvas [0] .getContext ('2d');
          // clear image already drawn on canvas
          ctx.clearRect (0,0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
          // draw thumbnails on canvas
          ctx.drawImage (image, 0,0, image.THUMBNAIL_WIDTH, image.THUMBNAIL_HEIGHT, 0,0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
          // Get base64 image data from canvas
          base64 = canvas.get (0) .toDataURL ('image/jpeg');
          console.log (base64);// For testing
        }
        image.src = e.target.result;
      }
      reader.readAsDataURL (file);
    });

    // When the upload start button is clicked
    $('# upload'). click (function () {
      $.ajax ({
        url: "http: // localhost: 8080/upload", // destination
        type: 'POST',
        dataType: 'json',
        data: {
          "src": base64,
        },


        processData: false,
        contentType: false
      })
      .done (function (data, textStatus, jqXHR) {
        // successful transmission
      })
      .fail (function (jqXHR, textStatus, errorThrown) {
        // Transmission failure
      });
    });
  });
  </script>
</body>
</html>

How can I receive JSON?
Thank you.

Supplemental information (FW/tool version etc.)

Node.js v12.13.0
npm v6.12.0
Express v4.16.1

Browser used: Google Chrome

  • Answer # 1

    Since the JSON that should have been sent has not been sent, the cause is thought to be on the client side, and when the client side was investigated, the cause was found.

    Cause Code before modification

    Excerpts

    $. ajax ({
            url: "http: // localhost: 8080/upload", // destination
            type: 'POST',
            dataType: 'json',
            data: {"src": base64},
            processData: false,
            contentType: false,
          })

    $. ajax ()options setprocessDataandcontentTypetofalseSeems to have been bad.

    AboutprocessData

      

    By default, the data passed to the data option as an object (strictly speaking, something other than a character string) is formatted according to the default content-type "application/x-www-form-urlencoded" Will convert it to a query string. If you want to send DOMDocument or other format data, set this option to false.

    Source
    I want to send something other than JSON! It seems to be good to set it tofalseat that time.

    Aboutcontent-type

      

    Type:StringInitial value:application/x-www-form-urlencoded;charset = UTF-8
      The content type specified here is specified when data is sent to the server. The default is "application/x-www-form-urlencoded;charset = UTF-8", which is fine for most cases. If you explicitly pass content-type to $.ajax (), it will always be sent to the server. The W3C XMLHttpRequest specification (even when no data is sent) specifies that charset is always UTF-8, and does not force the browser to change the encoding of other charsets. (I am not confident in translation)

    Source
    Send with this kind! I'm not sure ... If you want to send JSON, it seems to be good to set the initial value.

    Modified source code

    Excerpts

    $.ajax ({
            url: "http: // localhost: 8080/upload", // destination
            type: 'POST',
            dataType: 'json',
            data: {"src": base64},
          })

    Neat code ^^

    You can't copy and paste code. I have to understand it properly.

    Thank you for the answer!