Search code examples
javascriptnode.jsfs

Uploading a blob with nodejs


Im struggling with uploading my pdf file to my server with nodejs help.

My code:

app.post("/sendFile", function(req, res) {
   var stream = fs.createWriteStream(path.join(__dirname, 'public', req.body.name + ".pdf"));
    stream.once('open', function () {
       stream.write(req.body.file);
       stream.end();
   });
});

However, the file which is being uploaded, is a Blob. Nodejs docs say that .write function accepts <string> | <Buffer> | <Uint8Array> as the first argument. Will it acept also a Blob? If not, which other function should I use to properly upload a Blob into my server?

Thank you.

Edit: or maybe I should change Blob into something else?


Solution

  • This is very easy to do with the multer module for Express. We'll also add a test .html file to the directory (client side JavaScript).

    To test this out, run node server.js, then navigate to http://localhost:8081 in your browser.

    server.js

    const express = require('express');
    const multer = require('multer');
    const upload = multer();
    const fs = require('fs');
    
    var app = express();
    app.use(express.static(__dirname));
    
    app.post('/post_pdf/', upload.any(), (req, res) => {
        console.log('POST /post_pdf/');
        console.log('Files: ', req.files);
        fs.writeFile(req.files[0].originalname, req.files[0].buffer, (err) => {
            if (err) {
                console.log('Error: ', err);
                res.status(500).send('An error occurred: ' + err.message);
            } else {
                res.status(200).send('ok');
            }
        });
    });
    
    app.listen(process.env.PORT || 8081);
    

    index.html

    <html>
    <head>
          <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
          <script>
    
                var fileData = null;
    
                function loadFile() {
                    var preview = document.querySelector('file');
                    var file    = document.querySelector('input[type=file]').files[0];
                    var reader  = new FileReader();
    
                    reader.onloadend = function () {
                        fileData = file;
                    }
                    if (file) {
                        reader.readAsDataURL(file);
                    }
                }
    
                function uploadFile() {
                    data = new FormData();
                    data.append('file', fileData);
    
                    $.ajax({
                      url: "/post_pdf/",
                      type: "POST",
                      data: data,
                      enctype: 'multipart/form-data',
                      processData: false,
                      contentType: false,
                      success: function(data) {
                          document.getElementById("result").innerHTML = 'Result: Upload successful';
                      },
                      error: function(e) {
                          document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
                      }
                    });
                }
    
          </script>
    </head>
    <body>
    <input type="file" onchange="loadFile()"><br>
    <button onclick="uploadFile()">Upload..</button>
    <div id='result'></div>
    </body>
    </html>