Serve xlsx file from MongoDB binary using Node.js












0














I have some Excel documents (xlsx) saved in MongoDB in binary. I would like node.js to retrieve a file from the database when a user navigates to a url and serve the file for the user to download. I'm successfully downloading a file, but I'm getting an error from Excel when trying to open the file:



"Excel cannot open the file '5beec8ef3cf3e70b5ce8972e.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."



The file is also saving with 0 bytes. I think I am not correctly converting the data from MongoDB before trying to create the buffer. Here's my script:



app.get('//downloadReport/:id', (req, res) => {
dbo = db.db('test');
dbo.collection("reports").findOne(
{'_id': mongodb.ObjectId(req.params.id)}
).then(doc => {

console.log('type of doc.file: ' + typeof doc.file);
// returns:
// type of doc.file: object

console.log(doc.file);
// returns:
// Binary {
// _bsontype: 'Binary',
// sub_type: 0,
// position: 1146504,
// buffer: <Buffer 50 4b 03 04 14 00 00 00 08 00 12 66 6f 4d f8 64 19 ... > }


res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);

// This one doesn't work
// res.end(doc.file, 'binary');
// returns:
// TypeError: First argument must be a string or Buffer

res.end(new Buffer(doc.file, 'binary') );
});
});


I've tried drilling down to doc.file.Binary.buffer, but I get an error saying doc.file.Binary is not defined.



I also want the file to download with the correct file name. I've tried adding this to writeHead:



['Content-disposition', 'filename=' + doc.filename]


but I get an error in Chrome: ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION



Anyone know how to make this work? Thanks in advance!










share|improve this question



























    0














    I have some Excel documents (xlsx) saved in MongoDB in binary. I would like node.js to retrieve a file from the database when a user navigates to a url and serve the file for the user to download. I'm successfully downloading a file, but I'm getting an error from Excel when trying to open the file:



    "Excel cannot open the file '5beec8ef3cf3e70b5ce8972e.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."



    The file is also saving with 0 bytes. I think I am not correctly converting the data from MongoDB before trying to create the buffer. Here's my script:



    app.get('//downloadReport/:id', (req, res) => {
    dbo = db.db('test');
    dbo.collection("reports").findOne(
    {'_id': mongodb.ObjectId(req.params.id)}
    ).then(doc => {

    console.log('type of doc.file: ' + typeof doc.file);
    // returns:
    // type of doc.file: object

    console.log(doc.file);
    // returns:
    // Binary {
    // _bsontype: 'Binary',
    // sub_type: 0,
    // position: 1146504,
    // buffer: <Buffer 50 4b 03 04 14 00 00 00 08 00 12 66 6f 4d f8 64 19 ... > }


    res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);

    // This one doesn't work
    // res.end(doc.file, 'binary');
    // returns:
    // TypeError: First argument must be a string or Buffer

    res.end(new Buffer(doc.file, 'binary') );
    });
    });


    I've tried drilling down to doc.file.Binary.buffer, but I get an error saying doc.file.Binary is not defined.



    I also want the file to download with the correct file name. I've tried adding this to writeHead:



    ['Content-disposition', 'filename=' + doc.filename]


    but I get an error in Chrome: ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION



    Anyone know how to make this work? Thanks in advance!










    share|improve this question

























      0












      0








      0







      I have some Excel documents (xlsx) saved in MongoDB in binary. I would like node.js to retrieve a file from the database when a user navigates to a url and serve the file for the user to download. I'm successfully downloading a file, but I'm getting an error from Excel when trying to open the file:



      "Excel cannot open the file '5beec8ef3cf3e70b5ce8972e.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."



      The file is also saving with 0 bytes. I think I am not correctly converting the data from MongoDB before trying to create the buffer. Here's my script:



      app.get('//downloadReport/:id', (req, res) => {
      dbo = db.db('test');
      dbo.collection("reports").findOne(
      {'_id': mongodb.ObjectId(req.params.id)}
      ).then(doc => {

      console.log('type of doc.file: ' + typeof doc.file);
      // returns:
      // type of doc.file: object

      console.log(doc.file);
      // returns:
      // Binary {
      // _bsontype: 'Binary',
      // sub_type: 0,
      // position: 1146504,
      // buffer: <Buffer 50 4b 03 04 14 00 00 00 08 00 12 66 6f 4d f8 64 19 ... > }


      res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);

      // This one doesn't work
      // res.end(doc.file, 'binary');
      // returns:
      // TypeError: First argument must be a string or Buffer

      res.end(new Buffer(doc.file, 'binary') );
      });
      });


      I've tried drilling down to doc.file.Binary.buffer, but I get an error saying doc.file.Binary is not defined.



      I also want the file to download with the correct file name. I've tried adding this to writeHead:



      ['Content-disposition', 'filename=' + doc.filename]


      but I get an error in Chrome: ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION



      Anyone know how to make this work? Thanks in advance!










      share|improve this question













      I have some Excel documents (xlsx) saved in MongoDB in binary. I would like node.js to retrieve a file from the database when a user navigates to a url and serve the file for the user to download. I'm successfully downloading a file, but I'm getting an error from Excel when trying to open the file:



      "Excel cannot open the file '5beec8ef3cf3e70b5ce8972e.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."



      The file is also saving with 0 bytes. I think I am not correctly converting the data from MongoDB before trying to create the buffer. Here's my script:



      app.get('//downloadReport/:id', (req, res) => {
      dbo = db.db('test');
      dbo.collection("reports").findOne(
      {'_id': mongodb.ObjectId(req.params.id)}
      ).then(doc => {

      console.log('type of doc.file: ' + typeof doc.file);
      // returns:
      // type of doc.file: object

      console.log(doc.file);
      // returns:
      // Binary {
      // _bsontype: 'Binary',
      // sub_type: 0,
      // position: 1146504,
      // buffer: <Buffer 50 4b 03 04 14 00 00 00 08 00 12 66 6f 4d f8 64 19 ... > }


      res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);

      // This one doesn't work
      // res.end(doc.file, 'binary');
      // returns:
      // TypeError: First argument must be a string or Buffer

      res.end(new Buffer(doc.file, 'binary') );
      });
      });


      I've tried drilling down to doc.file.Binary.buffer, but I get an error saying doc.file.Binary is not defined.



      I also want the file to download with the correct file name. I've tried adding this to writeHead:



      ['Content-disposition', 'filename=' + doc.filename]


      but I get an error in Chrome: ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION



      Anyone know how to make this work? Thanks in advance!







      node.js mongodb binary






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 16:43









      Michael Cox

      2749




      2749
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I figured it out. I just needed to use doc.file.buffer and put double quotes (") around the filename.



          I found the buffer answer here: How to save file in Mongodb using Node.js



              res.writeHead(200, {
          'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'Content-Disposition': 'attachment; filename="' + doc.filename + '"'
          });

          res.end(new Buffer(doc.file.buffer, 'binary') );





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342088%2fserve-xlsx-file-from-mongodb-binary-using-node-js%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I figured it out. I just needed to use doc.file.buffer and put double quotes (") around the filename.



            I found the buffer answer here: How to save file in Mongodb using Node.js



                res.writeHead(200, {
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition': 'attachment; filename="' + doc.filename + '"'
            });

            res.end(new Buffer(doc.file.buffer, 'binary') );





            share|improve this answer




























              0














              I figured it out. I just needed to use doc.file.buffer and put double quotes (") around the filename.



              I found the buffer answer here: How to save file in Mongodb using Node.js



                  res.writeHead(200, {
              'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              'Content-Disposition': 'attachment; filename="' + doc.filename + '"'
              });

              res.end(new Buffer(doc.file.buffer, 'binary') );





              share|improve this answer


























                0












                0








                0






                I figured it out. I just needed to use doc.file.buffer and put double quotes (") around the filename.



                I found the buffer answer here: How to save file in Mongodb using Node.js



                    res.writeHead(200, {
                'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition': 'attachment; filename="' + doc.filename + '"'
                });

                res.end(new Buffer(doc.file.buffer, 'binary') );





                share|improve this answer














                I figured it out. I just needed to use doc.file.buffer and put double quotes (") around the filename.



                I found the buffer answer here: How to save file in Mongodb using Node.js



                    res.writeHead(200, {
                'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition': 'attachment; filename="' + doc.filename + '"'
                });

                res.end(new Buffer(doc.file.buffer, 'binary') );






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 16 '18 at 20:47

























                answered Nov 16 '18 at 20:00









                Michael Cox

                2749




                2749






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53342088%2fserve-xlsx-file-from-mongodb-binary-using-node-js%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to send String Array data to Server using php in android

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                    Is anime1.com a legal site for watching anime?