Uploading files using Vapor

痴心易碎 提交于 2020-01-02 01:25:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38988329/uploading-files-using-vapor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!