Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading files using Vapor

Tags:

vapor

I've seen in documentation in Body section that there's a support for file uploading right now - or at least I understand it this way 😅

I have no strong foundation in backend development - especially if it comes to frameworks which are still eveloving so fast as Vapor do. I wonder if someone can provide some real life example of file uploading? I was hoping for a simple web page with possibility to upload a file to the backend and then store it for future usage.

like image 373
cojoj Avatar asked Aug 17 '16 04:08

cojoj


1 Answers

Vapor allows for file upload using the Multipart encoding. You can read more about HTTP upload here:

How does HTTP file upload work?

And also here:

What does enctype='multipart/form-data' mean?

So the HTML code to upload a file to Vapor would look something like:

<form action="upload" method="POST" enctype="multipart/form-data">
    <input type="text" name="name">
    <input type="file" name="image">
    <input type="submit" value="Submit">
</form>

And then the code in Vapor

drop.get("form") { req in
    return try drop.view("form.html")
}

drop.post("upload") { req in
    let name = req.data["name"]
    let image = req.data["image"] // or req.multipart["image"]

    ...
}

In terms of how to store the image, that is up to you. You can store in a database or create a folder on the system to which you have write access.

like image 125
tanner0101 Avatar answered Sep 30 '22 17:09

tanner0101