Search code examples
webuploadframeworksdvibed

how to upload a file in vibe.d using the web framework


I am still new to Vibe.d so forgive me if I am missing something obvious.

I want to upload a file in Vibe.d using the web framework. However, all the examples I find, including the one in the book 'D Web Development', are not using the web framework. If I insert the non-web-framework example to my app, it crashes. It would suck if I have to abandon the web framework just for the sake of one feature, which is file upload.

The Vibe.d documentation is a good effort and I appreciate it but until now it is rather sparse and the examples are few and far between.

Here are some snippets of my code:

shared static this()
{
    auto router = new URLRouter;
    router.post("/upload", &upload);
    router.registerWebInterface(new WebApp);
    //router.get("/", staticRedirect("/index.html"));
    //router.get("/ws", handleWebSockets(&handleWebSocketConnection));
    router.get("*", serveStaticFiles("public/"));

    auto settings = new HTTPServerSettings;
    settings.port = 8080;
    settings.bindAddresses = ["::1", "127.0.0.1"];
    listenHTTP(settings, router);

    conn = connectMongoDB("127.0.0.1");
    appStore = new WebAppStore;
}

void upload(HTTPServerRequest req, HTTPServerResponse res)
{
    auto f = "filename" in req.files;
    try
    {
        moveFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
    }
    catch(Exception e) 
    {
        copyFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
    }
    res.redirect("/uploaded");
}

Can I still access the HTTPServerRequest.files using the web framework? How? Or do I still need it? Meaning, is there another way without using HTTPServerRequest.files?

Thanks a lot!


Solution

  • Put the upload function inside the WebApp class and use it to handle the form post form(action="/upload", method ="post")

    class WebApp {
    
        addUpload(HTTPServerRequest req, ...)
        {
            auto file = file in req.files;
            ...
        }
    }