RejectedSoftware Forums

Sign up

uploading a file with the web framework

Hi,

I am developing a web app that requires one who registers to upload a profile photo. All the uploading examples I see are not based on the web framework. Here are the snippets:

shared static this()
{

auto router = new URLRouter;
router.post("/upload", &upload);
router.registerWebInterface(new MyWebApp);
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");
myStore = new MyStore;

}

and I copy-pasted your example in upload():

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.writeBody("File uploaded!");
//res.redirect("/uploaded");

}

but my app crashes. I tried using a form that includes an input of type 'file' but I am getting nowhere.

So my question: How can I access HTTPServerRequest.files? Do I still need it when I am using the web framework? Is it still existing/visible when using the web framework?

Or to simplify my question: how do I upload a file when using the web framework?

Thanks for hearing me out!

Best regards,

Rey

Re: uploading a file with the web framework

On Fri, 16 Dec 2016 04:51:16 GMT, Rey Valeza wrote:

auto f = "filename" in req.files;
try
{
	moveFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}

...

but my app crashes. I tried using a form that includes an input of type 'file' but I am

See documentation about 'in' operator: https://dlang.org/spec/hash-map.html#testing_membership

You have to test f variable before any usage.

Side note: It is crucial to be able to catch memory errors when you work with D. Use next code in Linux environment and collect application's stdout and strerr to some log files to have trace for all cases of null pointer access or unhandled exceptions.

shared static this()
{
	import etc.linux.memoryerror;
	static if (is(typeof(registerMemoryErrorHandler)))
		registerMemoryErrorHandler();
...