Skip to content

Commit

Permalink
feat: better file type detection (#63)
Browse files Browse the repository at this point in the history
* chore: update dep

* feat: better file type detection
  • Loading branch information
rin-yato authored Mar 31, 2024
1 parent c26ff17 commit 936ccc7
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"eslint-plugin-jest": "^27.6.3",
"lucia": "^3.1.1",
"lucide-react": "^0.309.0",
"magic-bytes.js": "^1.10.0",
"next": "14.0.4",
"oslo": "^1.1.3",
"react": "^18",
Expand Down
15 changes: 10 additions & 5 deletions src/app/api/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { generateId } from "lucia";
import { ApiError } from "@/lib/api-error";
import { HttpStatus } from "@/constants/http-status";
import { env } from "@/env";
import { filetypeinfo } from "magic-bytes.js";

export const runtime = "edge";

Expand Down Expand Up @@ -61,20 +62,24 @@ export const POST = withUser(async ({ req, user }) => {
});
}

// we can do compression or resizing here and return a new buffer
const buffer = new Uint8Array(await file.arrayBuffer());

// e.g. image/png -> png
const fileExtenstion = file.type.split("/")[1] || "";
const fallbackFileType = file.type.split("/")[1] || "";
const fallbackExtension = file.name.split(".").pop() || fallbackFileType;

// we can do compression or resizing here and return a new buffer
const buffer = Buffer.from(await file.arrayBuffer());
const { extension = fallbackExtension, mime = file.type } =
filetypeinfo(buffer)[0];

// hash the content and append the file extension
const hashedFilename = concat(await hash(buffer), ".", fileExtenstion);
const hashedFilename = concat(await hash(buffer), ".", extension);

const uploadToR2 = await R2.upload({
buffer,
userId: user.id,
filename: hashedFilename,
contentType: file.type,
contentType: mime,
})
.then(ok)
.catch(err);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/r2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async function upload({
filename,
contentType,
}: {
buffer: Buffer;
buffer: Buffer | Uint8Array;
userId: string;
filename: string;
contentType: string;
Expand Down

0 comments on commit 936ccc7

Please sign in to comment.