简体   繁体   English

如何使用 Web 框架在 vibe.d 中上传文件

[英]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.我还是 Vibe.d 的新手,所以如果我遗漏了一些明显的东西,请原谅我。

I want to upload a file in Vibe.d using the web framework.我想使用 Web 框架在 Vibe.d 中上传文件。 However, all the examples I find, including the one in the book 'D Web Development', are not using the web framework.但是,我找到的所有示例,包括“D Web 开发”一书中的示例,都没有使用 Web 框架。 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.如果我仅仅为了一个功能,即文件上传而不得不放弃 Web 框架,那就太糟糕了。

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. Vibe.d 文档是一项很好的工作,我很欣赏它,但直到现在它相当稀疏并且示例很少而且相距甚远。

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?我仍然可以使用 Web 框架访问 HTTPServerRequest.files 吗? How?如何? Or do I still need it?还是我还需要它? Meaning, is there another way without using HTTPServerRequest.files?意思是,有没有另一种不使用 HTTPServerRequest.files 的方法?

Thanks a lot!非常感谢!

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:确保在表单的 enctype 中声明“multipart/form-data”:

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:在 web 框架类的 postNewEmployee() 方法中,通过 request.files 获取文件:

auto pic = "picture" in request.files;

Here is a sample postNewEmployee() method being passed an Employee struct:这是一个示例 postNewEmployee() 方法,它传递了一个 Employee 结构:

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:当我再次尝试学习Vibe.d时,我再次意识到教程的缺乏,所以我自己写了一个教程,作为学习者一切都很新鲜:

https://github.com/reyvaleza/vibed https://github.com/reyvaleza/vibed

Hope you find this useful.希望您觉得这个有帮助。

Put the upload function inside the WebApp class and use it to handle the form post form(action="/upload", method ="post")将上传函数放在 WebApp 类中,并使用它来处理表单 post form(action="/upload", method ="post")

class WebApp {

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

You can try hunt-framework , Hunt Framework is a high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design.你可以试试 Hunt -framework ,Hunt Framework 是一个高级 D 编程语言 Web 框架,它鼓励快速开发和干净、务实的设计。 It lets you build high-performance Web applications quickly and easily.它使您可以快速轻松地构建高性能 Web 应用程序。

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM