javascriptnode.jsexpressblob

How to send a Blob with other type of data to NodeJS ExpressJS


I searched all the last day an API to send Datas, from Javascript Client Side to the my NodeJS server with express, code below.

app.post('/microphone', express.raw({type: "*/*", limit: '1000000mb' }), function(req, res)
{    
    var buffer = req.body.buffer;

    var nbrVoice = req.body.nbrVoice;
    var codeUser = req.body.codeUser;
    
    var dirUsers = "users/"+codeUser+"/";

        
    fs.appendFileSync(( dirUsers +nbrVoice+ '_microphone.wav'), buffer );

      res.send( "Okay wav file saved );

});

I have a server with expressjs and I want to send a DataView or a Blob with two number

[blob,  codeUser, nbrVoice ]

I tried with xmlhttprequest, a modern version of that call fetch but that not worked and i am blocked with the raw binary data to string to buffer datas on the server.

if someone have an idea I search a code without jquery.


Solution

  • You could send the file as base64 string, but why bother: simply use the tools for that case: form data on the client, and multer on the express.

    Example: append file and other data to FormData, and on the server use multer to process both file (stored in req.file) and other data (stored in req.body), you can save file in memory and then use req.file.buffer to save it (check multer documentation, you can process file completely in corresponding methods (destination etc.), there you can also access req.body and generate filename, limit size etc.:

    // client
    let formData = new FormData();
    
    formData.append('codeUser', 'codeUser');
    formData.append('nbrVoice', 'nbrVoice');
    formData.append('file', YourBlob);
    
    fetch('/microphone', {
            method: 'POST',
            body: formData,
        }).then(async(result) => {
            console.log(await result.text());
        })
        .catch((error) => {
            console.log(error);
    
        });
    
       // server
       // setup multer, with in memory option here
        const storage = multer.memoryStorage();
        const upload = multer({ storage });
        
        // read `file` field from formdata
        app.post('/microphone', upload.single('file'), (req, res)=>{
        console.log(req.file, req.body);
    
        var buffer = req.file.buffer;
    
        var nbrVoice = req.body.nbrVoice;
        var codeUser = req.body.codeUser;
    
        var dirUsers = "users/"+codeUser+"/";
    
        fs.appendFileSync(( dirUsers +nbrVoice+ '_microphone.wav'), buffer );
    
        res.send( "Okay wav file saved ");
    });