Skip to content

Commit

Permalink
fix: update the api to hash the buffer instead of filename
Browse files Browse the repository at this point in the history
  • Loading branch information
rin-yato committed Feb 17, 2024
1 parent 8cde836 commit ab87fc2
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/app/api/upload/file/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@ export const POST = async (request: NextRequest) => {
const size = file.size;
const fileType = file.type;
const fileExtenstion = file.type.split("/")[1] || "";
const hashedFilename = concat(md5(file.name), ".", fileExtenstion);

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

const url = await R2.upload(buffer, hashedFilename, fileType)
// hash the content and append the file extension
const hashedContent = concat(md5(buffer), ".", fileExtenstion);

const url = await R2.upload(buffer, hashedContent, fileType)
.then(ok)
.catch(err);

Expand All @@ -49,7 +51,7 @@ export const POST = async (request: NextRequest) => {

const userUploadParams = insertUserUploadSchema.safeParse({
userId: session.user.id,
hashedFilename: hashedFilename,
hash: hashedContent,
filename: file.name,
size,
} satisfies NewUserUpload);
Expand Down
7 changes: 4 additions & 3 deletions src/app/api/upload/url/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ export const POST = async (request: NextRequest) => {
const fileType = blob.type;
const fileExtenstion = fileType.split("/").pop() || "";
const size = blob.size;
const hashedFilename = concat(md5(filename), ".", fileExtenstion);

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

const url = await R2.upload(buffer, hashedFilename, fileType)
const hashedContent = concat(md5(buffer), ".", fileExtenstion);

const url = await R2.upload(buffer, hashedContent, fileType)
.then(ok)
.catch(err);

Expand All @@ -48,7 +49,7 @@ export const POST = async (request: NextRequest) => {

const userUploadParams = insertUserUploadSchema.safeParse({
userId: session.user.id,
hashedFilename: hashedFilename,
hash: hashedContent,
filename: filename,
size,
} satisfies NewUserUpload);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/md5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ import crypto from "crypto";
* @param input - string to hash
* @returns md5 hashed string
*/
export const md5 = (input: string) => {
export const md5 = (input: crypto.BinaryLike) => {
return crypto.createHash("md5").update(input).digest("hex");
};

0 comments on commit ab87fc2

Please sign in to comment.