0

I am using multer to store files in local storage and then picking them according and sending them back currently for some reason files are sending as buffer (i am using postman to view them) . And i also need to send json data alongside the file.

In below example i commented the resFile code which is not working as expected. And i am just sending json data with res.send.

My file structure is like this for reference

~root 
   -controllers folder (route callback logic here) 
   -storage (with files i need to fetch)
   -route.js file 
   -app.js file (entry point),
   -etc.


try{
            const template =  await Template.findOne({
                where : {
                    user_id : req.user.dataValues.id,
                    template_id : req.params.id 
                }
            }).then((data)=>{
                let dataJSON = {
                    id : data.dataValues.id,
                    user_id : data.dataValues.user_id,
                    template_id : data.dataValues.template_id,
                    title : data.dataValues.title,
                    customizations : JSON.parse(data.dataValues.customizations),
                    attachments : JSON.parse(data.dataValues.attachments)
                }
                let name = path.parse(dataJSON.attachments[0].path).name;
                let ext = path.parse(dataJSON.attachments[0].path).ext;
                console.log(name);
                if(data){
                    // res.sendFile(name+ext,{root :path.join('storage','')},(err)=>{
                    //     if (err) throw err;
                    // });
                    res.send({
                        success : true,
                        data : dataJSON
                    })
                }else{
                    if(err) throw err;
                    res.status(403).send({
                        success : false,
                        message : 'Template Doesnt exist'
                    });
                }
            });
        }
Mayank Singh Fartiyal
  • 867
  • 1
  • 11
  • 26

1 Answers1

0

What you are looking to do is send multipart/mixed responses from your server. If the response is going to a client you control and can modify to handle these responses you should be ok, but browser support for them will be hit & miss at best. If you search for "multipart responses" you will find an assortment of discussion on the topic, many of them in Stack Overflow. One with some sample code is here.. multipart/mixed response using NodeJS

lecstor
  • 5,619
  • 21
  • 27
  • @Iecstor but sending files and json data with multipart content is possible from client side , parsing it is also possible but sending the same from server side to client side is not? – Mayank Singh Fartiyal Nov 08 '17 at 18:19
  • it is possible, but will be unreliable unless you control the client. – lecstor Nov 08 '17 at 21:21