-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageUpload.tsx
108 lines (95 loc) · 3.07 KB
/
ImageUpload.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
import { ChangeEvent, useEffect, DragEvent, useState } from "react";
import Image from "next/image";
interface ImageUploadProps {
file: File | null;
setFile: (prop: File) => void;
}
const ImageUpload = ({ file, setFile }: ImageUploadProps) => {
const [ismobile, setIsMobile] = useState(false);
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
const selectedFile: File = e.target.files[0];
setFile(selectedFile);
}
};
const handleSelectFile = () => {
const fileInput = document.createElement("input");
if (fileInput) {
fileInput.type = "file";
fileInput.style.display = "none";
document.body.appendChild(fileInput);
fileInput.click();
fileInput.addEventListener("change", (event: Event) => {
// Get the first selected file.
const target = event.target as HTMLInputElement;
// Access the `files` property.
const files = target.files as any;
for (const file of files) {
// If the file is not null, set it.
if (file !== null) {
setFile(file);
}
}
});
}
};
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
const selectedFile: File = e.dataTransfer.files[0];
setFile(selectedFile);
};
const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
};
useEffect(() => {
setIsMobile(window.innerWidth < 640);
}, []);
return (
<div>
{!ismobile ? (
<div
onDrop={handleDrop}
onDragOver={handleDragOver}
className=" border-2 border-dashed border-white h-[100px] text-center rounded text-white cursor-pointer w-full"
onClick={handleSelectFile}
>
{file ? (
<div className=" flex flex-row justify-between pr-6 py-2 pl-2 items-center h-full max-md:items-center w-full">
<p className=" font-bold flex flex-col items-start max-md:hidden">
<span className=" ">selected file:</span>
<span className="underline text-gray-500 leading-tight">
{file.name}
</span>
</p>
<Image
src={URL.createObjectURL(file)}
alt="Selected Image"
width={75}
height={80}
loading="lazy"
className="rounded-xl"
/>
</div>
) : (
<p className="h-full w-full flex flex-col justify-center items-center text-center text-white font-bold ">
Drag and drop an image or{" "}
<span className=" w-[50px] bg-neutral-magnolia text-black font-bold rounded-lg">
click
</span>{" "}
to select one.
</p>
)}
</div>
) : (
<input
type="file"
accept="image/*"
id="fileInput"
onChange={handleFileChange}
className=" w-full"
/>
)}
</div>
);
};
export default ImageUpload;