How I successfully uploaded a file using Vue and Sails ⛵️
Ever had one of those moments when you feel like doing the chicken dance and saying “yes! yes!!!” until people around feel you are losing your marshmallows? Well, I had one of those a few minutes after I painstakingly figured out how to successfully upload images using VueJS to my Sails Web service.
Indeed I wish I had found the solutions from the Sails community but no one was answering me so I figured it out(isn’t that what we do mostly as developers). Let me show you how I did it!
Prelude — Sails Action
So I have a Sails web service and upload actions(look out for my article where I explain why I use actions instead of controllers)
So my upload.js action contains the code below:
The Vue Side of Things
Now to the meat. I found out that Sails was not really the problem but the issue was with my browser and my Vue code. Let me show you:
My template P.S: I am using SFC:
Looks pretty easy right? But let me explain how I got to this — First, using fetch I normally specify the content type of my POST request but I discovered doing that when using the type of multipart/form-data, Sails didn’t seem to get access to the payload, Why? I think it has something to do with boundary(a mechanism which the server would use to get an individual piece of your request payload. So what did I do? I allowed the browser to handle that by not specifying it in the request options. And that was the Silver bullet!
Conclusion
It was a learnable moment and what really helped me was Advance Rest Client(ARC) I stumbled upon it in my search for answers and after using it to hit my upload endpoint I had the idea to remove the content type and bam! I got it!
I hope this helps you and do look out for more Sails and Vue recipe from me. Also, leave a comment if you have a question. 😃
Learn about FormData here
Happy deploying 🚀 🚀 🚀