index.dt
doctype html
head
title File upload
body
form(method='post', action='/upload', enctype='multipart/form-data')
label(for='file') file
br
input(name='file', type='file')
br
button(type='submit') Send
upload.dt
doctype html
head
title File upload
body
br
-foreach(f; images)
text(name='title')=f
br
img(src=f)
br
app.d:
import vibe.vibe;
import std.stdio : writeln;
import std.file : dirEntries, SpanMode;
final class Router
{
void postUpload(HTTPServerRequest req, HTTPServerResponse res)
{
auto file = "file" in req.files;
try {
moveFile(file.tempPath, Path("./public/uploads") ~ file.filename);
writeln("Uploaded successfully!");
}
catch (Exception e) {
writeln("Exception thrown, trying copy");
copyFile(file.tempPath, Path("./public/uploads") ~ file.filename);
}
auto images = dirEntries("./public/uploads",SpanMode.shallow)
.map!(f=> f.name).array;
images.writeln;
render!("upload.dt", images);
}
}
void main()
{
auto router = new URLRouter;
router.registerWebInterface(new Router);
router.get("/", staticTemplate!"index.dt");
router.get("*", serveStaticFiles("./public/"));
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);
runEventLoop;
logInfo("Server Running");
}
When trying to render
images
The contents are printed via
f
and
images.writeln;
But the actual images are broken/404'd in
img(src=f)
as shown here: upload test
I'm not sure if it's something silly I'm overlooking, or a fundamental concept I just don't know about. The vibed-github didn't seem to have anything in the examples, nor in the docs, unless i missed it.
Also keep in mind this is just a quick and dirty prototype to get things working.
But I'd appreciate any advice/insight for a more "proper" version.
Thanks in advance.