-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileInputSample.tsx
117 lines (106 loc) · 3.01 KB
/
FileInputSample.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
109
110
111
112
113
114
115
116
117
import { FC, useState, useRef } from "react";
import { useForm } from "react-hook-form";
const isMobile = window.navigator.userAgent.toLowerCase().includes("mobile");
const FileInputSample: FC = () => {
const fileInput = useRef<HTMLInputElement | null>(null);
const [fileName, setFileName] = useState("");
const [imageData, setImageData] = useState("");
const {
handleSubmit,
register,
formState: { errors },
} = useForm();
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length <= 0) return;
deployment(files);
};
const { ref, ...rest } = register("file", {
onChange,
required: "ファイルを選択してください",
});
const selectFile = () => {
if (!fileInput.current) return;
fileInput.current.removeAttribute("capture");
fileInput.current.click();
};
const camera = () => {
if (!fileInput.current) return;
fileInput.current.setAttribute("capture", "environment");
fileInput.current.click();
};
// ファイルを選択した時の処理
const deployment = (files: FileList) => {
const file = files[0];
const fileReader = new FileReader();
setFileName(file.name);
fileReader.onload = () => {
setImageData(fileReader.result as string);
};
fileReader.readAsDataURL(file);
};
// クローズボタンをクリックしたときの動作
const reset = () => {
setFileName("");
setImageData("");
if (fileInput.current) {
fileInput.current.value = "";
}
};
const onSubmit = (values: any) => {
console.log(values);
alert("OK");
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h1>File Input Sample</h1>
<div style={{ textAlign: "center", padding: "1em" }}>
<input
type="file"
id="file"
ref={(e) => {
ref(e);
fileInput.current = e;
}}
accept="image/*"
style={{ display: "none" }}
{...rest}
/>
<button onClick={selectFile} type="button">
📁 ファイルから選択
</button>
<button onClick={camera} type="button" disabled={!isMobile}>
📷 カメラで撮影
</button>
<div
style={{
padding: "1em",
border: "1px dotted #ccc",
minHeight: "200px",
background: "#eee",
}}
>
{fileName && (
<>
<img
src={imageData}
style={{ margin: "auto", maxWidth: "100%" }}
/>
<div>{fileName}</div>
<button onClick={reset}>❌ CLOSE</button>
</>
)}
</div>
<div>
{errors.file && (
<span style={{ color: "red" }}>
{errors.file?.message?.toString()}
</span>
)}
</div>
<button type="submit">🔥 SUBMIT</button>
</div>
</form>
);
};
export default FileInputSample;