-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.tsx
108 lines (98 loc) · 3 KB
/
upload.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"use client";
import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Upload } from "lucide-react";
import { cn } from "@/lib/utils";
import axios from "axios";
import { useAuth } from "@/lib/useAuth";
import Loading from "./loading";
import { showToast } from "@/lib/showToast";
interface Props {
className?: string;
fileName: string | null;
setFileName: (value: string | null) => void;
}
const FileUpload: React.FC<Props> = ({
className,
setFileName,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const { session } = useAuth();
const [loading, setLoading] = useState<boolean>(false);
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
const newFormData = new FormData();
if (file && session?.user) {
newFormData.append("file", file);
newFormData.append("userId", JSON.stringify({ userId: session.user.id }));
onUpload(file.name, newFormData);
}
};
const handleButtonClick = () => {
fileInputRef.current?.click();
};
const clearFile = () => {
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
setFileName(null);
};
const onUpload = async (newFileName: string, newFormData: FormData) => {
showToast(`Uploading ${newFileName}...`, "", "default");
try {
setLoading(true);
const azureFunctionURL =
process.env.NEXT_PUBLIC_AZURE_UPLOAD_FUNCTION_URL!;
if (newFormData) await axios.post(azureFunctionURL, newFormData);
setLoading(false);
showToast(`Successfully uploaded ${newFileName}`, "", "good");
clearFile();
setFileName(newFileName);
} catch (error: any) {
setLoading(false);
showToast(
`Failed to upload ${newFileName} :(`,
"Please try again...",
"destructive"
);
} finally {
setLoading(false);
}
};
return (
<>
<div
className={cn("w-full", className)}
>
<div className="relative">
<Input
type="file"
id="file-upload"
className="sr-only"
onChange={handleFileChange}
ref={fileInputRef}
aria-describedby="file-description"
/>
<div className="flex flex-row items-center">
<Button
type="button"
onClick={handleButtonClick}
className="w-full py-7 px-7 sm:py-5 sm:px-4 sm:text-xl text-2xl fg-grad text-black border-none relative hover:brightness-[115%] rounded-2xl transition-all duration-300"
>
{loading ? (
<Loading width={24} height={24} stroke={3} />
) : (
<>
<Upload className="w-5 h-5 mr-2" strokeWidth={2.75} />
Upload
</>
)}
</Button>
</div>
</div>
</div>
</>
);
};
export default FileUpload;