From 81e71adad60c0fa83bc430677d2910785d0184fc Mon Sep 17 00:00:00 2001 From: Casey Ydenberg Date: Fri, 24 Nov 2023 14:50:50 -0800 Subject: [PATCH] docs: Add file upload example (Concepts/Forms) (#2064) (#2065) --- docs/latest/concepts/forms.md | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/docs/latest/concepts/forms.md b/docs/latest/concepts/forms.md index 307d82bd..02c56fb6 100644 --- a/docs/latest/concepts/forms.md +++ b/docs/latest/concepts/forms.md @@ -56,3 +56,56 @@ export default function Subscribe() { When the user submits the form, Deno will access a specific `email` value from a `formData()`, add the email to a list, and redirect the user to a thank you page. + +## Handling file uploads + +File uploads can be handled in a very similar manner to the example above. Note +that this time, we have to explicitly declare the form's encoding. + +```tsx routes/subscribe.tsx +import { Handlers } from "$fresh/server.ts"; + +export const handler: Handlers = { + async GET(req, ctx) { + return await ctx.render(); + }, + async POST(req, ctx) { + const form = await req.formData(); + const file = form.get("my-file") as File; + + if (!file) { + return ctx.render({ + message: `Please try again`, + }); + } + + const name = file.name; + const contents = await file.text(); + + console.log(contents); + + return ctx.render({ + message: `${myFile.name} uploaded!`, + }); + }, +}; + +export default function Upload() { + return ( + <> +
+ + +
+ {message ?

{message}

: null} + + ); +} +``` + +## A note of caution + +These examples are simplified to demonstrate how Deno and Fresh handle HTTP +requests. In the Real World™, you'll want to validate your data (_especially the +file type_) and protect against cross-site request forgery. Consider yourself +warned.