NodeJS - multer - change filename depending on request attributes





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I know that I can change the filename with multer by means of the storage object like following:



const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, process.env.UPLOAD_DIR);
},
filename: (req, file, cb) => {
cb(null, 'bla.png');
}
});
const upload = multer({ storage: storage } );


My request, besides having the file, also contains some text attributes such as name: myPic.png.



Is it possible to dynamically change the filename dependent on other request attributes or within the controller like following:



filename: (req, file, cb) => {
cb(null, `${req.body.name}.png`);
}


or



router.post('/upload', upload.single('pic'), myController.upload);

/* in controller */
upload = async (req: Request, res: Response) => {
try {

/* change the filename of multer here? */

} catch (err) {
winston.error(`Error while uploading: ${err.message}`);
winston.error(`Stack trace: ${err.stack}`);
sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
}
}









share|improve this question





























    0















    I know that I can change the filename with multer by means of the storage object like following:



    const storage = multer.diskStorage({
    destination: (req, file, cb) => {
    cb(null, process.env.UPLOAD_DIR);
    },
    filename: (req, file, cb) => {
    cb(null, 'bla.png');
    }
    });
    const upload = multer({ storage: storage } );


    My request, besides having the file, also contains some text attributes such as name: myPic.png.



    Is it possible to dynamically change the filename dependent on other request attributes or within the controller like following:



    filename: (req, file, cb) => {
    cb(null, `${req.body.name}.png`);
    }


    or



    router.post('/upload', upload.single('pic'), myController.upload);

    /* in controller */
    upload = async (req: Request, res: Response) => {
    try {

    /* change the filename of multer here? */

    } catch (err) {
    winston.error(`Error while uploading: ${err.message}`);
    winston.error(`Stack trace: ${err.stack}`);
    sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    }









    share|improve this question

























      0












      0








      0








      I know that I can change the filename with multer by means of the storage object like following:



      const storage = multer.diskStorage({
      destination: (req, file, cb) => {
      cb(null, process.env.UPLOAD_DIR);
      },
      filename: (req, file, cb) => {
      cb(null, 'bla.png');
      }
      });
      const upload = multer({ storage: storage } );


      My request, besides having the file, also contains some text attributes such as name: myPic.png.



      Is it possible to dynamically change the filename dependent on other request attributes or within the controller like following:



      filename: (req, file, cb) => {
      cb(null, `${req.body.name}.png`);
      }


      or



      router.post('/upload', upload.single('pic'), myController.upload);

      /* in controller */
      upload = async (req: Request, res: Response) => {
      try {

      /* change the filename of multer here? */

      } catch (err) {
      winston.error(`Error while uploading: ${err.message}`);
      winston.error(`Stack trace: ${err.stack}`);
      sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      }









      share|improve this question














      I know that I can change the filename with multer by means of the storage object like following:



      const storage = multer.diskStorage({
      destination: (req, file, cb) => {
      cb(null, process.env.UPLOAD_DIR);
      },
      filename: (req, file, cb) => {
      cb(null, 'bla.png');
      }
      });
      const upload = multer({ storage: storage } );


      My request, besides having the file, also contains some text attributes such as name: myPic.png.



      Is it possible to dynamically change the filename dependent on other request attributes or within the controller like following:



      filename: (req, file, cb) => {
      cb(null, `${req.body.name}.png`);
      }


      or



      router.post('/upload', upload.single('pic'), myController.upload);

      /* in controller */
      upload = async (req: Request, res: Response) => {
      try {

      /* change the filename of multer here? */

      } catch (err) {
      winston.error(`Error while uploading: ${err.message}`);
      winston.error(`Stack trace: ${err.stack}`);
      sendJSONResponse(res, err, HttpStatus.INTERNAL_SERVER_ERROR);
      }
      }






      javascript node.js file-upload multer






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 26 '18 at 18:27









      phoebusphoebus

      311113




      311113
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Multer is the middleware which both populates req.body AND stores the file.



          Also, when it reaches the filename() function, there is no guarantee that the text fields will be populated in req.body because it depends on which order the client sends them in (see last note).



          From what I see, you have two options:



          1) Rename the uploaded file after the multer upload middleware does its thing and populates req.body as well as req.file. So in your controller upload middleware, you'd do something like:



          if (req.file) {
          fs.renameSync(req.file.path, req.file.destination + req.body.name);
          }


          2) Change the request body text field into a query parameter. Then, inside filename() you can do a req.query.name.



          Con: Not a very RESTful design, but maybe that is not so important to you.






          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%2f53487001%2fnodejs-multer-change-filename-depending-on-request-attributes%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














            Multer is the middleware which both populates req.body AND stores the file.



            Also, when it reaches the filename() function, there is no guarantee that the text fields will be populated in req.body because it depends on which order the client sends them in (see last note).



            From what I see, you have two options:



            1) Rename the uploaded file after the multer upload middleware does its thing and populates req.body as well as req.file. So in your controller upload middleware, you'd do something like:



            if (req.file) {
            fs.renameSync(req.file.path, req.file.destination + req.body.name);
            }


            2) Change the request body text field into a query parameter. Then, inside filename() you can do a req.query.name.



            Con: Not a very RESTful design, but maybe that is not so important to you.






            share|improve this answer




























              0














              Multer is the middleware which both populates req.body AND stores the file.



              Also, when it reaches the filename() function, there is no guarantee that the text fields will be populated in req.body because it depends on which order the client sends them in (see last note).



              From what I see, you have two options:



              1) Rename the uploaded file after the multer upload middleware does its thing and populates req.body as well as req.file. So in your controller upload middleware, you'd do something like:



              if (req.file) {
              fs.renameSync(req.file.path, req.file.destination + req.body.name);
              }


              2) Change the request body text field into a query parameter. Then, inside filename() you can do a req.query.name.



              Con: Not a very RESTful design, but maybe that is not so important to you.






              share|improve this answer


























                0












                0








                0







                Multer is the middleware which both populates req.body AND stores the file.



                Also, when it reaches the filename() function, there is no guarantee that the text fields will be populated in req.body because it depends on which order the client sends them in (see last note).



                From what I see, you have two options:



                1) Rename the uploaded file after the multer upload middleware does its thing and populates req.body as well as req.file. So in your controller upload middleware, you'd do something like:



                if (req.file) {
                fs.renameSync(req.file.path, req.file.destination + req.body.name);
                }


                2) Change the request body text field into a query parameter. Then, inside filename() you can do a req.query.name.



                Con: Not a very RESTful design, but maybe that is not so important to you.






                share|improve this answer













                Multer is the middleware which both populates req.body AND stores the file.



                Also, when it reaches the filename() function, there is no guarantee that the text fields will be populated in req.body because it depends on which order the client sends them in (see last note).



                From what I see, you have two options:



                1) Rename the uploaded file after the multer upload middleware does its thing and populates req.body as well as req.file. So in your controller upload middleware, you'd do something like:



                if (req.file) {
                fs.renameSync(req.file.path, req.file.destination + req.body.name);
                }


                2) Change the request body text field into a query parameter. Then, inside filename() you can do a req.query.name.



                Con: Not a very RESTful design, but maybe that is not so important to you.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 26 '18 at 22:30









                VasanVasan

                3,76631433




                3,76631433
































                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53487001%2fnodejs-multer-change-filename-depending-on-request-attributes%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

                    Wiesbaden

                    Marschland

                    Dieringhausen