-
Notifications
You must be signed in to change notification settings - Fork 0
/
extra_code.txt
74 lines (61 loc) · 1.97 KB
/
extra_code.txt
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
// after taking file input converting file to base64 format and pushing to /api/upload
const [file, setFile] = useState<File | null>(null);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0] || null;
setFile(selectedFile);
};
const handleUpload = async () => {
if (!file) {
alert("Please select a file to upload.");
return;
}
const base64String = await fileToBase64(file);
const formData = new FormData();
formData.append("file", base64String);
const filename = file.name;
formData.append("filename", filename);
console.log(filename);
console.log(base64String);
try {
const response = await fetch("/api/upload", {
method: "POST",
body: formData,
});
if (response.ok) {
alert("File uploaded successfully!");
} else {
alert("File upload failed.");
}
} catch (error) {
console.error("Error uploading file:", error);
alert("An error occurred while uploading the file.");
}
};
// File to base64 code
const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64 = reader.result?.toString().replace(/^data:.+;base64,/, '') || '';
resolve(base64); // Return the Base64 string
};
reader.onerror = (error) => {
reject(error);
};
reader.readAsDataURL(file);
});
};
// Taking input and uploading it to /documents
<input
type="file"
onChange={handleFileChange}
className="mb-4 p-2 border border-gray-400 rounded"
/>
<Link href={"/documents"}>
<button
onClick={handleUpload}
className="px-4 py-3 m-3 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Upload
</button>
</Link>