Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Patrickkx Avatar asked Aug 13 '18 14:08

Patrickkx


People also ask

How do I upload images to Blob storage?

From the left menu, select Storage accounts, then select the name of your storage account. Select Containers, then select the thumbnails container. Select Upload to open the Upload blob pane. Choose a file with the file picker and select Upload.

Does node support Blob?

Yeah, but a blob isn't a native Node. js type.. You know, Number, String, Boolean, Object, Array, etc.


1 Answers

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>
like image 111
Terry Lennox Avatar answered Sep 25 '22 11:09

Terry Lennox