最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uploading a blob with nodejs - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Aug 13, 2018 at 15:56 Patrickkx asked Aug 13, 2018 at 14:50 PatrickkxPatrickkx 1,8709 gold badges38 silver badges66 bronze badges 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) – Patrickkx 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? – Jason Cust 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? – Patrickkx Commented Aug 13, 2018 at 15:56
  • 1 May be it is resolved in: stackoverflow./questions/39677993/… – Cesar Morillas Commented Nov 11, 2022 at 0:15
Add a ment  | 

1 Answer 1

Reset to default 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./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>
发布评论

评论列表(0)

  1. 暂无评论