简体   繁体   中英

How can I show multiple data containing picture and text data with JQUERY/AJAX, which are sent as object or array?

I can't find a solution how to handle an object or an array sent from a server and containing binary picture and text data with JQUERY/AJAX

Ok, here is the server side:

const url= require('url'),
      express = require('express'),
      fs = require ('fs'),
      app = express();
// Create a server

app.listen(8080, function (){
    console.log('Server running at http://127.0.0.1:8080/');
});

app.use (express.static (__dirname +'/public')); // provide public data,here: jQuery


app.get ("/", function (req, res){
    res.sendFile (__dirname +"/ClientServerExchange (2.5).html");
    console.log (__dirname +req.url);
});

app.get ("/image", function (req, res) {
    message = req.query.message;
    console.log (message);
    fs.readFile (message,  
    (err, myImg) => {
        var myData = {myImage: myImg, myText: "this a nice pic"};
//      var myData = [myImg, "this a nice pic"]; // if to be sent as array ...
        return res.send (myData);
    });

})

The client side:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" >
        <title>Client-Server Exchange</title>
        <script src="JS/jquery-3.5.0.js"></script>
        <style>

        </style>
        <script type='text/javascript'>

            $(document).ready (function (){

                const message = encodeURI("../Workbench/Pics/myPic.jpg");

                $.ajax({
                    url: "/image?message=" +message,
                    dataType: 'json',
                    xhr: function(){// Seems like the only way to get access to the xhr object
                        var xhr = new XMLHttpRequest();
                        xhr.ResponseType = 'blob';
                        return xhr;
                    },
                    success: function(data){
                        console.log ("Request sent");
                        var blobData = new Blob ([data.myImage]);
                        src = URL.createObjectURL(blobData);
                        $("img").attr ("src", src); 
                        $("#addComment").text (data.myText);
                    },
                    timeout: 10000
                });
            });
        </script>
    </head>
    <body>
        <p>show a picture from my little server </p>
        <img src ="">
        <p id="addComment"></p>
    </body>
</html>

The request is sent and I assume the response from the server contains all data. I can see it from the messages in both consoles. But no picture is shown, only a small symbol instead, which looks like a broken picture. The requested text appears after this symbol. There is no error message on client and server side.

The only way to receive picture data is as shown in the xhr structure inside the $.ajax function. I found the solution here at the stackoverflow platform. Client script works well, if I send picture data only (of course with slight modifications of the client and server script, but this is not the question here).

How can I program the client script, that it receives such an object and shall treat the myImage -part as a blob and the myText -part as a text?

Thanks in advance for your help.

Following to Babak's tip of using express.Router() I modified the program in my request a little bit.

Add to server program

const router = express.Router ();

app.use ("/image", router);

Replace there app.get ("/image", function (req, res) { ...}); with

router.get ("/", function (req, res) {
    message = req.query.message;
    console.log (message);
    fs.readFile (message,  
    (err, myImage) => {
        return res.send (myImage);
    }); 
});

and add

router.get ("/Title", function (req, res) {
    res.send ("This is a nice pic!");
})

On client side replace $.ajax({ ... }); with

                $.ajax({
                    url: "/image?message=" +message,
                    xhr: function(){// Seems like the only way to get access to the xhr object
                        var xhr = new XMLHttpRequest();
                        xhr.responseType = 'blob';
                        return xhr;
                    },
                    success: function(data){
                        console.log ("Request sent");
//                      var blobData = new Blob([data]); // not necessary
//                      var url = window.URL || window.webkitURL;
                        src = URL.createObjectURL(data); // could be blobData, if defined, but works also without this.
                        $("img").attr ("src", src);                 
                    }
                });

and add below this inside $(document).ready (function (){ ... })

                $.get ("/image/Title", function (data) {
                    $("#addComment").text (data);
                })

Obviously it is not possible to send binary data inside an object or array (I'm not sure, because I think to have read this, but I don't know where ...). Anyway, the solution above works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM