Skip to content

Commit

Permalink
✨ feat: 成功上传文件到 S3
Browse files Browse the repository at this point in the history
  • Loading branch information
rdmclin2 committed Jun 25, 2024
1 parent 2941823 commit 66fad94
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 6 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
"next": "^14.2.4",
"next-pwa": "^5.6.0",
"openai": "^4.52.0",
"pino": "^9.2.0",
"polished": "^4.3.1",
"query-string": "^9.0.0",
"react": "^18.3.1",
Expand Down
22 changes: 22 additions & 0 deletions src/app/trpc/edge/[trpc]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import type { NextRequest } from 'next/server';

import { pino } from '@/libs/logger';
import { edgeRouter } from '@/server/routers';

export const runtime = 'edge';

const handler = (req: NextRequest) =>
fetchRequestHandler({
endpoint: '/trpc/edge',

onError: ({ error, path }) => {
pino.info(`Error in tRPC handler (edge) on path: ${path}`);
console.error(error);
},

req,
router: edgeRouter,
});

export { handler as GET, handler as POST };
5 changes: 5 additions & 0 deletions src/libs/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Pino from 'pino';

export const pino = Pino({
level: process.env.LOG_LEVEL ? process.env.LOG_LEVEL : 'info',
});
3 changes: 0 additions & 3 deletions src/server/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ export class S3 {
});
}

public getClient() {
return this.client;
}
public async createPreSignedUrl(key: string): Promise<string> {
const command = new PutObjectCommand({
ACL: 'public-read',
Expand Down
9 changes: 6 additions & 3 deletions src/services/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,22 @@ import { uuid } from '@/utils/uuid';

export const upload = async (file: File) => {
const dateFolder = dayjs().format('YYYY/MM/DD'); // 使用当前日期作为文件夹名称
const folderName = `files/${dateFolder}`; // e.g., "uploads/2023-10-10"
const folderName = `files/${dateFolder}`; // e.g., "files/2023/10/10"
const fileName = `${uuid()}.${file.name.split('.').at(-1)}`;

const pathname = `${folderName}/${fileName}`;

const url = await edgeClient.upload.createS3PreSignedUrl.mutate({ pathname });

const formData = new FormData();
formData.append('file', file);

const res = await fetch(url, {
body: file.stream(),
body: file,
headers: {
'Content-Type': file.type,
},
method: 'POST',
method: 'PUT',
});

if (res.ok) {
Expand Down

0 comments on commit 66fad94

Please sign in to comment.