Skip to content

Commit

Permalink
fix: content-disposition filename regexp (#87)
Browse files Browse the repository at this point in the history
* Fix: Improve Content-Disposition filename matcher - handle white space + extended filename* in UTF-8

---------

Co-authored-by: maxime.abehserra <[email protected]>
  • Loading branch information
Waxoussou and maxime.abehserra authored Nov 13, 2024
1 parent ed4b243 commit 1df94a9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function normalizeMetadata(input?: File | Response | BufferLike | StreamL
}
if (input instanceof Response) {
const contentDisposition = input.headers.get("content-disposition")
const filename = contentDisposition && contentDisposition.match(/;\s*filename\*?=["']?(.*?)["']?$/i)
const filename = contentDisposition && contentDisposition.match(/;\s*filename\*?\s*=\s*(?:UTF-\d+''|)["']?([^;"'\r\n]*)["']?(?:;|$)/i);
const urlName = filename && filename[1] || input.url && new URL(input.url).pathname.split("/").findLast(Boolean)
const decoded = urlName && decodeURIComponent(urlName)
// @ts-ignore allow coercion from null to zero
Expand Down
10 changes: 9 additions & 1 deletion test/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,19 @@ Deno.test("normalizeMetadata needs a filename along Responses with insufficient

Deno.test("normalizeMetadata guesses filename from Content-Disposition", () => {
const metadata = normalizeMetadata(new Response("four", {
headers: { "content-disposition": "attachment; filename=test.txt" }
headers: { "content-disposition": "attachment; filename=test.txt; size=0" }
}))
assertEquals(metadata, { uncompressedSize: 0n, encodedName, nameIsBuffer: false })
})

Deno.test("normalizeMetadata guesses filename from non latin Content-Disposition", () => {
const metadata = normalizeMetadata(new Response("four", {
headers: { "content-disposition": "attachment; filename* = UTF-8''%CF%8C%CE%BD%CE%BF%CE%BC%CE%B1%20%CE%B1%CF%81%CF%87%CE%B5%CE%AF%CE%BF%CF%85.txt" }
}))
assertEquals(metadata, { uncompressedSize: 0n,encodedName: new TextEncoder().encode("όνομα αρχείου.txt"), nameIsBuffer: false })
})


Deno.test("normalizeMetadata guesses filename from a Response URL", () => {
const response = Object.create(Response.prototype, {
url: { get() { return "https://example.com/path/test.txt" } },
Expand Down

0 comments on commit 1df94a9

Please sign in to comment.