Skip to content

Commit ad4a0c0

Browse files
authored
feat: add file upload feature, 서버와 연결
feat: add file upload feature, 서버와 연결
2 parents 243c447 + 222c903 commit ad4a0c0

File tree

6 files changed

+105
-54
lines changed

6 files changed

+105
-54
lines changed

frontend/api/upload.tsx

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
const BASE_URL="http://0.0.0.0:8000"
3+
const AUTH_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxfQ.J8Qj4p5xrAMj0GKjddGky-oeAOlWxjT8KOCisXzSOdU"
4+
5+
6+
export async function uploadFile(file: File): Promise<string> {
7+
const formData = new FormData();
8+
formData.append("audio_file", file); // 필드 이름을 FastAPI와 동일하게 설정
9+
10+
//임시지정, 수정해야함(아마도 url에서 뽑는 방식)
11+
const toUserId=1;
12+
13+
14+
// `to_user_id`를 URL의 쿼리 파라미터로 추가
15+
const url = `${BASE_URL}/voice?to_user_id=${toUserId}`;
16+
17+
try {
18+
const response = await fetch(url, {
19+
method: "POST",
20+
headers: {
21+
Authorization: `Bearer ${AUTH_TOKEN}`, // 인증 토큰 추가
22+
},
23+
body: formData,
24+
});
25+
26+
if (!response.ok) {
27+
const errorText = await response.text();
28+
throw new Error(
29+
`Failed to upload file: HTTP ${response.status}, ${errorText}`
30+
);
31+
}
32+
33+
const result = await response.json();
34+
console.log("Upload result:", result);
35+
return result.message || "File uploaded successfully!";
36+
37+
} catch (error) {
38+
if (error instanceof Error) {
39+
throw new Error(`Upload failed: ${error.message}`);
40+
}
41+
throw new Error("An unknown error occurred during upload.");
42+
}
43+
}

frontend/components/send/SectionUpload.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Handlers, PageProps } from "$fresh/server.ts";
22
import UploadResult from "../../islands/uploadResult.tsx";
3-
import Upload from "./upload.tsx";
3+
import Upload from "../../islands/upload.tsx";
44

55
export default function SectionUpload() {
66
return (
@@ -12,7 +12,7 @@ export default function SectionUpload() {
1212
<div className={"px-2 my-2 flex flex-col gap-2 items-center"}>
1313
<h2 className={"hidden"}>Send</h2>
1414
<h3>Send a file</h3>
15-
<Upload message={"Upload a text file"} />
15+
<Upload initialMessage="Upload a text file" />
1616
</div>
1717
</div>
1818
<div className={"w-2 h-full bg-slate-600 hidden md:block"}>

frontend/components/send/upload.tsx

-51
This file was deleted.

frontend/fresh.gen.ts

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as $Counter from "./islands/Counter.tsx";
1212
import * as $DropdownListForm from "./islands/DropdownListForm.tsx";
1313
import * as $Inbox from "./islands/Inbox.tsx";
1414
import * as $ProfileEdit from "./islands/ProfileEdit.tsx";
15+
import * as $upload from "./islands/upload.tsx";
1516
import * as $uploadResult from "./islands/uploadResult.tsx";
1617
import type { Manifest } from "$fresh/server.ts";
1718

@@ -29,6 +30,7 @@ const manifest = {
2930
"./islands/DropdownListForm.tsx": $DropdownListForm,
3031
"./islands/Inbox.tsx": $Inbox,
3132
"./islands/ProfileEdit.tsx": $ProfileEdit,
33+
"./islands/upload.tsx": $upload,
3234
"./islands/uploadResult.tsx": $uploadResult,
3335
},
3436
baseUrl: import.meta.url,

frontend/islands/upload.tsx

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { useState } from "preact/hooks";
2+
import { uploadFile } from "../api/upload.tsx";
3+
4+
5+
interface UploadProps {
6+
initialMessage?: string;
7+
}
8+
9+
export default function Upload({ initialMessage }: UploadProps) {
10+
const [message, setMessage] = useState(initialMessage || "");
11+
async function handleFormSubmit(event: Event) {
12+
event.preventDefault(); // 기본 form 동작 방지
13+
14+
const form = event.target as HTMLFormElement;
15+
const input = form.elements.namedItem("my-file") as HTMLInputElement;
16+
console.log("Input element:", input); // input 요소가 제대로 가져와졌는지 확인
17+
const file = input.files?.[0];
18+
console.log("Selected file:", file); // 선택된 파일이 제대로 가져와졌는지 확인
19+
20+
if (!file) {
21+
setMessage("No file selected!");
22+
return;
23+
}
24+
25+
try {
26+
const resultMessage = await uploadFile(file);
27+
setMessage(resultMessage);
28+
} catch (error) {
29+
if (error instanceof Error) {
30+
setMessage(`Error: ${error.message}`);
31+
} else {
32+
setMessage("An unknown error occurred!");
33+
}
34+
}
35+
}
36+
37+
return (
38+
<>
39+
<form
40+
method="post"
41+
encType="multipart/form-data"
42+
className={"flex flex-row gap-2 items-center"}
43+
onSubmit={handleFormSubmit} // 폼 제출 이벤트 핸들러 추가
44+
>
45+
<div>
46+
<input type="file" name="my-file" accept=".mp3"/>
47+
</div>
48+
<div>
49+
<button className={"bg-red-400"} type="submit">
50+
Upload
51+
</button>
52+
</div>
53+
</form>
54+
{message ? <p>{message}</p> : null}
55+
</>
56+
);
57+
}

frontend/routes/send/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { useEffect } from "preact/hooks";
2-
import Upload from "../../components/send/upload.tsx";
2+
import Upload from "../../islands/upload.tsx";
33
import SectionUpload from "../../components/send/SectionUpload.tsx";
44
import ChevronBg from "../../components/chevronBg.tsx";
55
import TitleDivider from "../../components/common/TitleDivider.tsx";

0 commit comments

Comments
 (0)