8

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?

4
  • @JC97 I dont want to encode my Blob into base64. It will be an overkill (hundreds of bits which need to be stored somewhere) Commented Aug 13, 2018 at 14:57
  • 1
    It appears you might be using express. If so, are you using multer to process the upload? Commented Aug 13, 2018 at 15:06
  • @JasonCust I edited my post, thats all I have there. Should I include multer? Will it help me? Commented Aug 13, 2018 at 15:56
  • 1
    May be it is resolved in: stackoverflow.com/questions/39677993/… Commented Nov 11, 2022 at 0:15

1 Answer 1

12

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>
Sign up to request clarification or add additional context in comments.

17 Comments

So I dont really need the stream? I've heard its a better option to use streams to upload files. Or nope?
I'd guess files of a few mbs should be fine to buffer and send, if they are maybe tens of megs it might be better to use streams. I'd suggest you test both, see what the performance of each is. The code is very much the same.
@Patrickkx Synchronously writing a file as shown in the example is a bit of a concern since this appears to be a web service. Because JavaScript is single threaded, using I/O events (writing the file in this case) synchronously will prevent this process from being able to handle any other concurrent requests. If you are only running one instance of this service to handle all of your requests, that means any other request would not be processed until the file was uploaded. This may not be a concern if your traffic is relatively low but you should be aware of it.
Good point @Jason, we can use an async write easily enough, though as you say it depends on the expected volume of requests.
Oh, client side, you should not need to change the server side code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.