The JS runtimes
Published in

The JS runtimes

Deno nuggets: Get uploaded file name

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to get uploaded file name from the content-disposition header?

// From HTTP headers{
"content-length": "288580",
"user-agent": "curl/7.79.1",
"accept": "*/*",
"content-type": "text/javascript",
"content-disposition": "attachment; filename=\"app.js\""
}
/* FILE CONTENTS SUPPRESSED */

Solution

Whether Oak is used or not, the Oak framework comes with a useful utility function to extract the file name out of the content-disposition header. The utility can be imported directly without importing the entire Oak framework.

Here is the code of a server using serve API, but extracting file name through Oak’s utility getFilename:

import { getFilename } from "https://deno.land/x/oak/content_disposition.ts";
import { serve } from "https://deno.land/std/http/mod.ts";
const reqHandler = (req: Request) => {
const fileName = getFilename(req.headers.get("content-disposition") || "");
return new Response(`Got file ${fileName}`);
};
serve(reqHandler);

Let’s run it:

> deno run --allow-net=:8000 app.ts 
Listening on http://localhost:8000/
> curl --data-binary "@./testdata/sample.js" http://localhost:8000 -H 'content-disposition: filename="app.js"'
Got file app.js

If multipart/form-data is used, the file name can be extracted directly:

import { serve } from "https://deno.land/std/http/mod.ts";const reqHandler = async (req: Request) => {
const uploadedFields = await req.formData();
let fileName;
for (const f of uploadedFields) {
if (f[1] instanceof File) {
fileName = f[0];
}
}
return new Response(`Got file ${fileName}`);
};
serve(reqHandler);

Let’s test it out:

> curl -F app.js="@./testdata/sample.js" -F b=c http://localhost:8000 -H 'content-disposition: attachment; filename="app.js"'
Got file app.js

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

Articles on the popular JS runtimes, Node.js, Deno, and Bun

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store