LoginSignup
9
1

More than 1 year has passed since last update.

Deno でファイルアップロードを受け取る

Posted at

Deno でファイルアップロードを受け取るには、Request object の formData メソッドを使います。

import { serve } from "https://deno.land/std@0.158.0/http/server.ts";

serve(async (req) => {
  const data = await req.formData();
  const file = data.get("file");
  const bytes = await new Response(file).arrayBuffer();
  const size = bytes.byteLength;
  console.log("Received file", file.name);
  console.log("byte size =", size);
  return Response.json({ filename: file.name, size });
});

await req.formData() で Web 標準 API の FormData オブジェクトが取得出来ます。

data.get("file") 呼び出しで、File object が取得出来ます (この File も Web 標準 API の File になっています)。

await new Response(file).arrayBuffer() で File の中身を取り出しています。この バイト列 (Uint8Array型) がファイルの内容になっているので、これを使って、保存するなり加工するなり必要な処理を実装する事が出来ます。

上のサーバーを立ち上げた状態で、以下のような curl コマンドで挙動を確認する事が出来ます(file.pdf というファイルがカレントディレクトリにある想定です)。

$ curl -i http://localhost:8000 -F "file=@file.pdf"
HTTP/1.1 100 Continue

HTTP/1.1 200 OK
content-type: application/json
vary: Accept-Encoding
content-length: 37
date: Sat, 01 Oct 2022 11:22:15 GMT

{"filename":"file.pdf","size":375676}
9
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
1