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

677 views Asked by At

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!

3

There are 3 answers

1
aberba On BEST ANSWER

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;
        ...
    }
}
0
Rey Karitoy On

I have totally forgotten about this question. I remember how frustrating it was when you cannot readily find an answer to a question that seems to be elementary to those who already know.

Make sure you state 'multipart/form-data' in the enctype of your form:

form(method="post", action="new_employee", enctype="multipart/form-data")

Then a field in that form should include an input field of type 'file', something like this:

input(type="file", name="picture")

In the postNewEmployee() method of your web framework class, get the file through request.files:

auto pic = "picture" in request.files;

Here is a sample postNewEmployee() method being passed an Employee struct:

void postNewEmployee(Employee emp)
{
    Employee e = emp;
    string photopath = "No photo submitted";
    auto pic = "picture" in request.files;
    if(pic !is null) 
    {
        string ext = extension(pic.filename.name);
        string[] exts = [".jpg", ".jpeg", ".png", ".gif"];
        if(canFind(exts, ext))
        {
            photopath = "uploads/photos/" ~ e.fname ~ "_" ~ e.lname ~ ext;
            string dir = "./public/uploads/photos/";
            mkdirRecurse(dir);
            string fullpath = dir ~ e.fname ~ "_" ~ e.lname ~ ext;
            try moveFile(pic.tempPath, NativePath(fullpath));
            catch (Exception ex) copyFile(pic.tempPath, NativePath(fullpath));
        }
    }
    e.photo = photopath;
    empModel.addEmployee(e);
    redirect("list_employees");
}

When I tried to learn Vibe.d again, I again became aware of the dearth of tutorials, so I wrote a tutorial myself while everything is fresh as a learner:

https://github.com/reyvaleza/vibed

Hope you find this useful.

0
zoujiaqing On

You can try hunt-framework, Hunt Framework is a high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performance Web applications quickly and easily.

Sample code for action:

    @Action
    string upload()
    {
        string message;

        if (request.hasFile("file1"))
        {
            auto file = request.file("file1");

            if (file.isValid())
            {
                // File save path: file.path()
                // Origin name: file.originalName()
                // File extension: file.extension()
                // File mimetype: file.mimeType()

                if (file.store("uploads/myfile.zip"))
                {
                    message = "upload is successed";
                }
                else
                {

                    message = "save as error";
                }
            }
            else
            {
                message = "file is not valid";
            }
        }
        else
        {
            message = "not get this file";
        }

        return message;
    }