#File Upload in Fresh

4 messages · Page 1 of 1 (latest)

green wedge
#

Hi, I'm trying to upload file and handle it with Fresh, and i don't know how to get file content and save it into a file on the server.
Do any have code snippets ?

My code atm :
/api/file

import {Handlers} from "$fresh/server.ts";

export const handler: Handlers = {
  async POST(req, ctx) {
    const data = await req.formData();
    console.log(data.get("file");

    return new Response("OK");
  },
};

// output : <file-name.ext>
import { Head } from "$fresh/runtime.ts";

export default function Home() {
  return (
    <>
      <Head>
        <title>Fresh App</title>
      </Head>
      <div class="p-4 mx-auto max-w-screen-md">
        <form action="/api/file" method="POST">
          <input type="file" name="file" />
          <input type="submit" value="Upload" />
        </form>
      </div>
    </>
  );
}
cedar arch
#

You'll have to add method="post" encType="multipart/form-data" to your form to send the file to the server properly. Then you can read out the file like so: ```js
const data = await req.formData();
const file = data.get("file");
const fileData = new Uint8Array(await file?.valueOf().arrayBuffer());
await Deno.writeFile(join(root, "testFile"),
fileData);

wintry pagoda
#

@cedar arch what is the TS type of file? TS thinks it's a string or Object.

wintry pagoda
#

I think I found it: Blob: